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
|
xijunlee/Undergraduate-Thesis-Project-master
|
gramsmithorth.m
|
.m
|
Undergraduate-Thesis-Project-master/new_algorithm(lxl)/CodeLSA/helper_functions/gramsmithorth.m
| 317 |
utf_8
|
324ed13d7bac9f741e39fc1a759a42ea
|
%function y=gramsmithorth(x)
% Returns Y the Gram-Smith orthogonalization of the colums of X
% Y and X have the same dimensions
function y=gramsmithorth(x)
[K,D]=size(x);
I=eye(K);
y=x(:,1)/norm(x(:,1));
for(i=2:D)
newcol=(I-y*y')*x(:,i);
newcol=newcol/norm(newcol);
y=[y newcol];
end
|
github
|
xijunlee/Undergraduate-Thesis-Project-master
|
spectralclusternormalcut_recursive.m
|
.m
|
Undergraduate-Thesis-Project-master/new_algorithm(lxl)/CodeLSA/helper_functions/spectralclusternormalcut_recursive.m
| 1,031 |
utf_8
|
358bebb8231c4e0eff3a3f5417ba9daf
|
%function group=spectralclusternormalcut_recursive(n,simMat)
%n final number of cluster
%simMat similarity matrix
function group=spectralclusternormalcut_recursive(n,simMat)
%trivial case with 1 cluster
if(n==1)
group=ones(size(simMat,1),1);
end
%initial bipartition with spectral clustering
group=spectralclusternormalcut(simMat);
%call spectral clustering recursively
for(i=2:n-1)
mincheeger=Inf; %init
%try to split each cluster
for(j=1:i)
clusterindeces=find(group==j);
[groupcluster,clustercheeger]=spectralclusternormalcut(simMat(clusterindeces,clusterindeces));
%if the cheeger constant is less than in the previous clusters
if(clustercheeger<mincheeger)
%save the new partition
mincheeger=clustercheeger;
minclusterindeces=clusterindeces;
mingroupcluster=groupcluster;
end
end
%update with the new partition
group(minclusterindeces(find(mingroupcluster==2)))=i+1;
end
|
github
|
xijunlee/Undergraduate-Thesis-Project-master
|
Misclassification.m
|
.m
|
Undergraduate-Thesis-Project-master/new_algorithm(lxl)/common_useage/Misclassification.m
| 747 |
utf_8
|
64f83e2c05684862aefe11a391531b35
|
%--------------------------------------------------------------------------
% This function takes the groups resulted from spectral clutsering and the
% ground truth to compute the misclassification rate.
% groups: [grp1,grp2,grp3] for three different forms of Spectral Clustering
% s: ground truth vector
% Missrate: 3x1 vector with misclassification rates of three forms of
% spectral clustering
%--------------------------------------------------------------------------
% Copyright @ Ehsan Elhamifar, 2012
%--------------------------------------------------------------------------
function Missrate = Misclassification(groups,s)
n = max(s);
for i = 1:size(groups,2)
Missrate(i,1) = missclassGroups( groups(:,i),s,n ) ./ length(s);
end
|
github
|
xijunlee/Undergraduate-Thesis-Project-master
|
BuildAdjacency.m
|
.m
|
Undergraduate-Thesis-Project-master/new_algorithm(lxl)/common_useage/BuildAdjacency.m
| 1,024 |
utf_8
|
efa00260bc61cb7ddb34720083fc8300
|
%--------------------------------------------------------------------------
% This function takes a NxN coefficient matrix and returns a NxN adjacency
% matrix by choosing the K strongest connections in the similarity graph
% CMat: NxN coefficient matrix
% K: number of strongest edges to keep; if K=0 use all the exiting edges
% CKSym: NxN symmetric adjacency matrix
%--------------------------------------------------------------------------
% Copyright @ Ehsan Elhamifar, 2012
%--------------------------------------------------------------------------
function [CKSym,CAbs] = BuildAdjacency(CMat,K)
if (nargin < 2)
K = 0;
end
N = size(CMat,1);
CAbs = abs(CMat);
CKSym = CAbs + CAbs';
% [Srt,Ind] = sort( CAbs,1,'descend' );
%
% if (K == 0)
% for i = 1:N
% CAbs(:,i) = CAbs(:,i) ./ (CAbs(Ind(1,i),i)+eps);
% end
% else
% for i = 1:N
% for j = 1:K
% CAbs(Ind(j,i),i) = CAbs(Ind(j,i),i) ./ (CAbs(Ind(1,i),i)+eps);
% end
% end
% end
%
% CKSym = CAbs + CAbs';
|
github
|
xijunlee/Undergraduate-Thesis-Project-master
|
thrC.m
|
.m
|
Undergraduate-Thesis-Project-master/new_algorithm(lxl)/common_useage/thrC.m
| 680 |
utf_8
|
1d57203ca466d32bcd882ce949a6fea8
|
%--------------------------------------------------------------------------
% Copyright @ Ehsan Elhamifar, 2012
%--------------------------------------------------------------------------
function Cp = thrC(C,ro)
if (nargin < 2)
ro = 1;
end
if (ro < 1)
N = size(C,2);
Cp = zeros(N,N);
[S,Ind] = sort(abs(C),1,'descend');
for i = 1:N
cL1 = sum(S(:,i));
stop = false;
cSum = 0; t = 0;
while (~stop)
t = t + 1;
cSum = cSum + S(t,i);
if ( cSum >= ro*cL1 )
stop = true;
Cp(Ind(1:t,i),i) = C(Ind(1:t,i),i);
end
end
end
else
Cp = C;
end
|
github
|
xijunlee/Undergraduate-Thesis-Project-master
|
missclassGroups.m
|
.m
|
Undergraduate-Thesis-Project-master/new_algorithm(lxl)/common_useage/missclassGroups.m
| 1,099 |
utf_8
|
fbb042310b95c08898c1c63f799c42db
|
%--------------------------------------------------------------------------
% [miss,index] = missclass(Segmentation,RefSegmentation,ngroups)
% Computes the number of missclassified points in the vector Segmentation.
% Segmentation: 1 by sum(npoints) or sum(ngroups) by 1 vector containing
% the label for each group, ranging from 1 to n
% npoints: 1 by ngroups or ngroups by 1 vector containing the number of
% points in each group.
% ngroups: number of groups
%--------------------------------------------------------------------------
% Copyright @ Ehsan Elhamifar, 2012
%--------------------------------------------------------------------------
function [miss,index] = missclassGroups(Segmentation,RefSegmentation,ngroups)
Permutations = perms(1:ngroups);
if(size(Segmentation,2)==1)
Segmentation=Segmentation';
end
miss = zeros(size(Permutations,1),size(Segmentation,1));
for k=1:size(Segmentation,1)
for j=1:size(Permutations,1)
miss(j,k) = sum(Segmentation(k,:)~=Permutations(j,RefSegmentation));
end
end
[miss,temp] = min(miss,[],1);
index = Permutations(temp,:);
|
github
|
xijunlee/Undergraduate-Thesis-Project-master
|
BuildAdjacency_N.m
|
.m
|
Undergraduate-Thesis-Project-master/new_algorithm(lxl)/common_useage/BuildAdjacency_N.m
| 996 |
utf_8
|
df787c53899c59842f3f1bd1ebdfcd56
|
%--------------------------------------------------------------------------
% This function takes a NxN coefficient matrix and returns a NxN adjacency
% matrix by choosing the K strongest connections in the similarity graph
% CMat: NxN coefficient matrix
% K: number of strongest edges to keep; if K=0 use all the exiting edges
% CKSym: NxN symmetric adjacency matrix
%--------------------------------------------------------------------------
% Copyright @ Ehsan Elhamifar, 2012
%--------------------------------------------------------------------------
function [CKSym,CAbs] = BuildAdjacency_N(CMat,K)
if (nargin < 2)
K = 0;
end
N = size(CMat,1);
CAbs = abs(CMat);
CKSym = CAbs + CAbs';
[Srt,Ind] = sort( CAbs,1,'descend' );
if (K == 0)
for i = 1:N
CAbs(:,i) = CAbs(:,i) ./ (CAbs(Ind(1,i),i)+eps);
end
else
for i = 1:N
for j = 1:K
CAbs(Ind(j,i),i) = CAbs(Ind(j,i),i) ./ (CAbs(Ind(1,i),i)+eps);
end
end
end
CKSym = CAbs + CAbs';
|
github
|
xijunlee/Undergraduate-Thesis-Project-master
|
DataProjection.m
|
.m
|
Undergraduate-Thesis-Project-master/new_algorithm(lxl)/common_useage/DataProjection.m
| 754 |
utf_8
|
b3a44fded67998f640ca13c7059a36ad
|
%--------------------------------------------------------------------------
% This function takes the D x N data matrix with columns indicating
% different data points and project the D dimensional data into a r
% dimensional subspace using PCA.
% X: D x N matrix of N data points
% r: dimension of the PCA projection, if r = 0, then no projection
% Xp: r x N matrix of N projectred data points
%--------------------------------------------------------------------------
% Copyright @ Ehsan Elhamifar, 2012
%--------------------------------------------------------------------------
function Xp = DataProjection(X,r)
if (nargin < 2)
r = 0;
end
if (r == 0)
Xp = X;
else
%[U] = svd(X,0);
[U,~,~] = svd(X,0);
Xp = U(:,1:r)' * X;
end
|
github
|
xijunlee/Undergraduate-Thesis-Project-master
|
SpectralClustering.m
|
.m
|
Undergraduate-Thesis-Project-master/new_algorithm(lxl)/common_useage/SpectralClustering.m
| 1,218 |
utf_8
|
1dd5da7a3aa9d8acc02e7bbdae976eaa
|
%--------------------------------------------------------------------------
% This function takes an adjacency matrix of a graph and computes the
% clustering of the nodes using the spectral clustering algorithm of
% Ng, Jordan and Weiss.
% CMat: NxN adjacency matrix
% n: number of groups for clustering
% groups: N-dimensional vector containing the memberships of the N points
% to the n groups obtained by spectral clustering
%--------------------------------------------------------------------------
% Copyright @ Ehsan Elhamifar, 2012
%--------------------------------------------------------------------------
function groups = SpectralClustering(CKSym,n)
warning off;
N = size(CKSym,1);
MAXiter = 1000; % Maximum number of iterations for KMeans
REPlic = 10; % Number of replications for KMeans
% Normalized spectral clustering according to Ng & Jordan & Weiss
% using Normalized Symmetric Laplacian L = I - D^{-1/2} W D^{-1/2}
DN = diag( 1./sqrt(sum(CKSym)+eps) );
LapN = speye(N) - DN * CKSym * DN;
[uN,sN,vN] = svd(LapN);
kerN = vN(:,N-n+1:N);
for i = 1:N
kerNS(i,:) = kerN(i,:) ./ norm(kerN(i,:)+eps);
end
groups = kmeans(kerNS,n,'maxiter',MAXiter,'replicates',REPlic,'EmptyAction','singleton');
|
github
|
Sina-Baharlou/Face-Recognition-master
|
loadset.m
|
.m
|
Face-Recognition-master/loadset.m
| 529 |
utf_8
|
6e8d8a9b5639a9c6163c645ca947877d
|
% Face Recognition using Independent Component Analysis (ICA)
% Created on Mar 2015
% Authors: Sid Ali Rezetane, Sina M. Baharlou, Harold Agudelo
% Load the first n *.pgm images in the specified directory to a matrix
function D = loadset(directory, n)
% get all pgm files in the specified directory
file_list = dir([directory '/*.pgm']);
images = {file_list.name};
% load the images and put it to a matrix
D = [];
for i = 1:n
D = [D, loadpgm(char(strcat(directory, images(i))))];
end
|
github
|
Sina-Baharlou/Face-Recognition-master
|
getN.m
|
.m
|
Face-Recognition-master/getN.m
| 357 |
utf_8
|
c9add1b05ed5de929739863a5b52559e
|
% Face Recognition using Independent Component Analysis (ICA)
% Created on Mar 2015
% Authors: Sid Ali Rezetane, Sina M. Baharlou, Harold Agudelo
function n = getN(x, thresh)
total_length = sum(x);
s = length(x);
for i = 1 : s
if ((sum(x(1: s - i)) / total_length) < thresh)
break
end
end
n = s - i + 1;
end
|
github
|
Sina-Baharlou/Face-Recognition-master
|
loadsetEx.m
|
.m
|
Face-Recognition-master/loadsetEx.m
| 538 |
utf_8
|
b8b9017ada92fd20d576d96700c834f5
|
% Face Recognition using Independent Component Analysis (ICA)
% Created on Mar 2015
% Authors: Sid Ali Rezetane, Sina M. Baharlou, Harold Agudelo
% Load the first n *.pgm images (with offset 'o') from the m specified directory to a matrix
function D = loadsetEx(directory, n, m, o)
D = [];
for i = 1:m
dirEx = sprintf(directory, i);
file_list = dir([dirEx '/*.pgm']);
images = {file_list.name};
for i = 1:n
D = [D, loadpgm(char(strcat(dirEx, images(i + o))))];
end
end
|
github
|
Sina-Baharlou/Face-Recognition-master
|
archOne.m
|
.m
|
Face-Recognition-master/archOne.m
| 1,484 |
utf_8
|
54509da21d46dddab333f0334e021d83
|
% Face Recognition using Independent Component Analysis (ICA)
% Created on Mar 2015
% Authors: Sid Ali Rezetane, Sina M. Baharlou, Harold Agudelo
function [b, r, u, w, a, m, evec] = archOne(filename, nImage, nClass, offset, thresh)
% constants
blockSize = 30; % infomax blockzize
epochs = 100; % infomax number of epochs
learnRate = 0.0005; % infomax learning rate
whitten = 1; % enable whittening
method = 1; % 1 - infoMax 2- fastICA
% loading the train dataset
disp('Loading the dataset...');
D = loadsetEx(filename, nImage, nClass, offset);
% calculate and subtract the mean
disp('calculate and subtract the mean...');
[zm, m] = subMean(D);
% calculate the eigenfaces
disp('calculate the eigenfaces');
[evec, eval] = eigenface(zm);
% reduce the dimension
dim = getN(eval, thresh);
disp(sprintf('reduce the dimention to %d components. preserves 99 percent of dataset variance.', dim));
evec = evec(:, 1:dim);
% calculate ICA
switch method
case 1
disp('Calculating Independent Components using infoMax...');
[u, A, w] = infomax(evec',blockSize,epochs,learnRate,whitten);
case 2
disp('Calculating Independent Components using FastICA...');
[u, A, w] = fastica(evec');
end
% calculate the Rm matrix
Rm = zm'*evec;
% calculate B matrix
Bmat = Rm * A;
b = Bmat;
r = Rm;
a = A;
end
|
github
|
Sina-Baharlou/Face-Recognition-master
|
eigenface.m
|
.m
|
Face-Recognition-master/eigenface.m
| 874 |
utf_8
|
e93314c7aefca4e72abe23c601da73f0
|
% Face Recognition using Independent Component Analysis (ICA)
% Created on Mar 2015
% Authors: Sid Ali Rezetane, Sina M. Baharlou, Harold Agudelo
% calculate the eigenvalues
% V is the matrix containing the eigen vectors
% E is the matrix containing the eigen values
function [V, E] = eigen(M)
% calculate the size of the matrix
m_size = size(M);
% calculate the covariance
c = 1 / (m_size(2) - 1) * (M'*M);%cov(M);
% calculate the eigen vectors of M'
[U, E] = eig(c);
% sort eigen vectors
[sorted_eig, index] = sort(sum(E));
index = fliplr(index);
sorted_eig = fliplr(sorted_eig);
V = U(:, [index]);
% calculate the eigen vectors for M
V = M * V;
% calcuate the eigen values
E = sqrt(sum(V .^ 2));
% normalize the eigenvectors
V = V ./ (ones(m_size(1), 1) * E);
E = sorted_eig;
end
|
github
|
Sina-Baharlou/Face-Recognition-master
|
annClassifier.m
|
.m
|
Face-Recognition-master/annClassifier.m
| 1,241 |
utf_8
|
1543fadcae097367c6eb8ce6a0c5702a
|
% Face Recognition using Independent Component Analysis (ICA)
% Created on Mar 2015
% Authors: Sid Ali Rezetane, Sina M. Baharlou, Harold Agudelo
% Solve an Input-Output Fitting problem with a Neural Network
% Script generated by NFTOOL
% Created Fri Feb 27 17:42:35 CET 2015
%
% This script assumes these variables are defined:
%
% p - input data.
% t - target data.
function [n, p] = annClassifier(inputs, targets, hiddenLayerSize)
% Create a Fitting Network
net = fitnet(hiddenLayerSize);
% Setup Division of Data for Training, Validation, Testing
net.divideParam.trainRatio = 70 / 100;
net.divideParam.valRatio = 15 / 100;
net.divideParam.testRatio = 15 / 100;
% Train the Network
[net, tr] = train(net, inputs, targets);
% Test the Network
outputs = net(inputs);
errors = gsubtract(targets, outputs);
performance = perform(net, targets, outputs);
p = performance;
% View the Network
view(net)
% Plots
% Uncomment these lines to enable various plots.
% figure, plotperform(tr)
% figure, plottrainstate(tr)
% figure, plotfit(net,inputs,targets)
% figure, plotregression(targets,outputs)
% figure, ploterrhist(errors)
n = net;
|
github
|
Sina-Baharlou/Face-Recognition-master
|
bvector.m
|
.m
|
Face-Recognition-master/bvector.m
| 333 |
utf_8
|
7c9b62b12df46bd4bb0d73084e45d011
|
% Face Recognition using Independent Component Analysis (ICA)
% Created on Mar 2015
% Authors: Sid Ali Rezetane, Sina M. Baharlou, Harold Agudelo
% create binary vector
% n = size of the vector
% m = index of high bit
function v = bvector(n, m)
% create vector
v = zeros(n, 1);
% put m element to high
v(m) = 1;
end
|
github
|
Sina-Baharlou/Face-Recognition-master
|
archTwo.m
|
.m
|
Face-Recognition-master/archTwo.m
| 1,493 |
utf_8
|
f63d726742d933bc4ba6a8a3368de93d
|
% Face Recognition using Independent Component Analysis (ICA)
% Created on Mar 2015
% Authors: Sid Ali Rezetane, Sina M. Baharlou, Harold Agudelo
function [b, r, u, w, a, m, evec] = archTwo(filename, nImage, nClass, offset, thresh)
% constants
blockSize = 50; % infomax blockzize
epochs = 100; % infomax number of epochs
learnRate = 0.0005; % infomax learning rate
whitten = 1; % enable whittening
method = 1; % 1 - infoMax 2- fastICA
% loading the train dataset
disp('Loading the dataset...');
D = loadsetEx(filename, nImage, nClass, offset);
% calculate and subtract the mean
disp('calculate and subtract the mean...');
[zm, m] = subMean(D);
% calculate the eigenfaces
disp('calculate the eigenfaces');
[evec, eval] = eigenface(zm);
% reduce the dimension
dim = getN(eval, thresh);
disp(sprintf('reduce the dimention to %d components. preserves 99 percent of dataset variance.', dim));
evec = evec(:, 1:dim);
% calculate the Rm matrix
Rm = zm'*evec;
% calculate ICA
switch method
case 1
disp('Calculating Independent Components using infoMax...');
[u, A, w] = infomax(Rm',blockSize,epochs,learnRate,true);
case 2
disp('Calculating Independent Components using FastICA...');
[u, A, w] = fastica(Rm');
end
% calculate B matrix
Bmat = u;
% Bmat=Rm*inv(Wi);
b = Bmat;
r = Rm;
a = A;
end
|
github
|
Sina-Baharlou/Face-Recognition-master
|
subMean.m
|
.m
|
Face-Recognition-master/subMean.m
| 398 |
utf_8
|
36da83bfa313a916a47de41cc1ba852d
|
% Face Recognition using Independent Component Analysis (ICA)
% Created on Mar 2015
% Authors: Sid Ali Rezetane, Sina M. Baharlou, Harold Agudelo
% subtract mean
% ZM= Zero-mean data
% M = data mean
function [ZM, M] = subMean(D)
% calculate the size of the matrix
m_size = size(D);
% calculate the mean (mean of each row)
M = mean(D');
ZM = D - (ones(m_size(2), 1) * M)';
end
|
github
|
Sina-Baharlou/Face-Recognition-master
|
whiten.m
|
.m
|
Face-Recognition-master/whiten.m
| 482 |
utf_8
|
39db5dc3857bdd2e2f574d70c83995a0
|
% Face Recognition using Independent Component Analysis (ICA)
% Created on Mar 2015
% Authors: Sid Ali Rezetane, Sina M. Baharlou, Harold Agudelo
% whiten the data
% x = input matrix
% X = output whitened data
% WZ = whiten matrix
function [X, WZ] = whiten(x)
% subtract the mean
[SM, M] = subMean(x);
% calculate the covariance matrix of data'
c = cov(SM');
% get the whiten matrix
WZ = 2 * inv(sqrtm(c));
% whiten the data
X = WZ * SM;
end
|
github
|
Sina-Baharlou/Face-Recognition-master
|
infomax.m
|
.m
|
Face-Recognition-master/infomax.m
| 1,321 |
utf_8
|
83e2df94c4c3f165c7055274864403be
|
% Face Recognition using Independent Component Analysis (ICA)
% Created on Mar 2015
% Authors: Sid Ali Rezetane, Sina M. Baharlou, Harold Agudelo
% calculate demixing matrix using infoMax algorithm
% x = input signal
% bs = block size
% epochs
% lr = learning rate
% wh = whittening the data
% ----
% W = demixing matrix
% A = mixing matrix
% U = independent signals
function [U, A, W] = infomax(x, blockSize, epochs, lr, wh)
% get the size of input matrix
[N, P] = size(x);
if (wh == true)
fprintf('Whitening input data...\n');
[x, wz] = whiten(x);
end
fprintf('Performing infoMax...\n');
% initialize W with random numbers near zero
W = randn(N) * 0.01;
% divide input signal to blocks of size 'blockSize'
blockCount = floor(P / blockSize);
% start the iteration
for i = 1:epochs
% update W for each block
for j = 1:blockSize:blockCount * blockSize
% calculate u
u = W * x(:, j:j + blockSize - 1);
% sigmoid activation function
y = 1 ./ (1 + exp(- u));
% update W
W = W + lr * ((eye(N) + (1 - 2 * y) * u')*W);
end
fprintf('.')
end
fprintf('\n');
U = W * x;
if (wh == true)
W = W * wz;
end
A = inv(W);
end
|
github
|
Sina-Baharlou/Face-Recognition-master
|
loadpgm.m
|
.m
|
Face-Recognition-master/loadpgm.m
| 577 |
utf_8
|
3db0f19d9b34f12491718bf34735c243
|
% Face Recognition using Independent Component Analysis (ICA)
% Created on Mar 2015
% Authors: Sid Ali Rezetane, Sina M. Baharlou, Harold Agudelo
% simply load the pgm file to the memory convert it to grayscale and reshape it to a vector
function X = loadpgm(filename)
% read the image file
img = imread(filename);
% convert it to gray scale ( also this convert the image to double)
gray = mat2gray(img);
% get image size
imsize = size(gray);
% reshape the image into single column vector
X = reshape(gray, [imsize(1) * imsize(2), 1]);
|
github
|
Sina-Baharlou/Face-Recognition-master
|
pcamat.m
|
.m
|
Face-Recognition-master/fica/pcamat.m
| 12,075 |
utf_8
|
bcb1117d4132558d0d54d8b7b616a902
|
function [E, D] = pcamat(vectors, firstEig, lastEig, s_interactive, ...
s_verbose);
%PCAMAT - Calculates the pca for data
%
% [E, D] = pcamat(vectors, firstEig, lastEig, ...
% interactive, verbose);
%
% Calculates the PCA matrices for given data (row) vectors. Returns
% the eigenvector (E) and diagonal eigenvalue (D) matrices containing the
% selected subspaces. Dimensionality reduction is controlled with
% the parameters 'firstEig' and 'lastEig' - but it can also be done
% interactively by setting parameter 'interactive' to 'on' or 'gui'.
%
% ARGUMENTS
%
% vectors Data in row vectors.
% firstEig Index of the largest eigenvalue to keep.
% Default is 1.
% lastEig Index of the smallest eigenvalue to keep.
% Default is equal to dimension of vectors.
% interactive Specify eigenvalues to keep interactively. Note that if
% you set 'interactive' to 'on' or 'gui' then the values
% for 'firstEig' and 'lastEig' will be ignored, but they
% still have to be entered. If the value is 'gui' then the
% same graphical user interface as in FASTICAG will be
% used. Default is 'off'.
% verbose Default is 'on'.
%
%
% EXAMPLE
% [E, D] = pcamat(vectors);
%
% Note
% The eigenvalues and eigenvectors returned by PCAMAT are not sorted.
%
% This function is needed by FASTICA and FASTICAG
% For historical reasons this version does not sort the eigenvalues or
% the eigen vectors in any ways. Therefore neither does the FASTICA or
% FASTICAG. Generally it seams that the components returned from
% whitening is almost in reversed order. (That means, they usually are,
% but sometime they are not - depends on the EIG-command of matlab.)
% @(#)$Id: pcamat.m,v 1.5 2003/12/15 18:24:32 jarmo Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Default values:
if nargin < 5, s_verbose = 'on'; end
if nargin < 4, s_interactive = 'off'; end
if nargin < 3, lastEig = size(vectors, 1); end
if nargin < 2, firstEig = 1; end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check the optional parameters;
switch lower(s_verbose)
case 'on'
b_verbose = 1;
case 'off'
b_verbose = 0;
otherwise
error(sprintf('Illegal value [ %s ] for parameter: ''verbose''\n', s_verbose));
end
switch lower(s_interactive)
case 'on'
b_interactive = 1;
case 'off'
b_interactive = 0;
case 'gui'
b_interactive = 2;
otherwise
error(sprintf('Illegal value [ %s ] for parameter: ''interactive''\n', ...
s_interactive));
end
oldDimension = size (vectors, 1);
if ~(b_interactive)
if lastEig < 1 | lastEig > oldDimension
error(sprintf('Illegal value [ %d ] for parameter: ''lastEig''\n', lastEig));
end
if firstEig < 1 | firstEig > lastEig
error(sprintf('Illegal value [ %d ] for parameter: ''firstEig''\n', firstEig));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Calculate PCA
% Calculate the covariance matrix.
if b_verbose, fprintf ('Calculating covariance...\n'); end
covarianceMatrix = cov(vectors', 1);
% Calculate the eigenvalues and eigenvectors of covariance
% matrix.
[E, D] = eig (covarianceMatrix);
% The rank is determined from the eigenvalues - and not directly by
% using the function rank - because function rank uses svd, which
% in some cases gives a higher dimensionality than what can be used
% with eig later on (eig then gives negative eigenvalues).
rankTolerance = 1e-7;
maxLastEig = sum (diag (D) > rankTolerance);
if maxLastEig == 0,
fprintf (['Eigenvalues of the covariance matrix are' ...
' all smaller than tolerance [ %g ].\n' ...
'Please make sure that your data matrix contains' ...
' nonzero values.\nIf the values are very small,' ...
' try rescaling the data matrix.\n'], rankTolerance);
error ('Unable to continue, aborting.');
end
% Sort the eigenvalues - decending.
eigenvalues = flipud(sort(diag(D)));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Interactive part - command-line
if b_interactive == 1
% Show the eigenvalues to the user
hndl_win=figure;
bar(eigenvalues);
title('Eigenvalues');
% ask the range from the user...
% ... and keep on asking until the range is valid :-)
areValuesOK=0;
while areValuesOK == 0
firstEig = input('The index of the largest eigenvalue to keep? (1) ');
lastEig = input(['The index of the smallest eigenvalue to keep? (' ...
int2str(oldDimension) ') ']);
% Check the new values...
% if they are empty then use default values
if isempty(firstEig), firstEig = 1;end
if isempty(lastEig), lastEig = oldDimension;end
% Check that the entered values are within the range
areValuesOK = 1;
if lastEig < 1 | lastEig > oldDimension
fprintf('Illegal number for the last eigenvalue.\n');
areValuesOK = 0;
end
if firstEig < 1 | firstEig > lastEig
fprintf('Illegal number for the first eigenvalue.\n');
areValuesOK = 0;
end
end
% close the window
close(hndl_win);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Interactive part - GUI
if b_interactive == 2
% Show the eigenvalues to the user
hndl_win = figure('Color',[0.8 0.8 0.8], ...
'PaperType','a4letter', ...
'Units', 'normalized', ...
'Name', 'FastICA: Reduce dimension', ...
'NumberTitle','off', ...
'Tag', 'f_eig');
h_frame = uicontrol('Parent', hndl_win, ...
'BackgroundColor',[0.701961 0.701961 0.701961], ...
'Units', 'normalized', ...
'Position',[0.13 0.05 0.775 0.17], ...
'Style','frame', ...
'Tag','f_frame');
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'BackgroundColor',[0.701961 0.701961 0.701961], ...
'HorizontalAlignment','left', ...
'Position',[0.142415 0.0949436 0.712077 0.108507], ...
'String','Give the indices of the largest and smallest eigenvalues of the covariance matrix to be included in the reduced data.', ...
'Style','text', ...
'Tag','StaticText1');
e_first = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'Callback',[ ...
'f=round(str2num(get(gcbo, ''String'')));' ...
'if (f < 1), f=1; end;' ...
'l=str2num(get(findobj(''Tag'',''e_last''), ''String''));' ...
'if (f > l), f=l; end;' ...
'set(gcbo, ''String'', int2str(f));' ...
], ...
'BackgroundColor',[1 1 1], ...
'HorizontalAlignment','right', ...
'Position',[0.284831 0.0678168 0.12207 0.0542535], ...
'Style','edit', ...
'String', '1', ...
'Tag','e_first');
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'BackgroundColor',[0.701961 0.701961 0.701961], ...
'HorizontalAlignment','left', ...
'Position',[0.142415 0.0678168 0.12207 0.0542535], ...
'String','Range from', ...
'Style','text', ...
'Tag','StaticText2');
e_last = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'Callback',[ ...
'l=round(str2num(get(gcbo, ''String'')));' ...
'lmax = get(gcbo, ''UserData'');' ...
'if (l > lmax), l=lmax; fprintf([''The selected value was too large, or the selected eigenvalues were close to zero\n'']); end;' ...
'f=str2num(get(findobj(''Tag'',''e_first''), ''String''));' ...
'if (l < f), l=f; end;' ...
'set(gcbo, ''String'', int2str(l));' ...
], ...
'BackgroundColor',[1 1 1], ...
'HorizontalAlignment','right', ...
'Position',[0.467936 0.0678168 0.12207 0.0542535], ...
'Style','edit', ...
'String', int2str(maxLastEig), ...
'UserData', maxLastEig, ...
'Tag','e_last');
% in the first version oldDimension was used instead of
% maxLastEig, but since the program would automatically
% drop the eigenvalues afte maxLastEig...
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'BackgroundColor',[0.701961 0.701961 0.701961], ...
'HorizontalAlignment','left', ...
'Position',[0.427246 0.0678168 0.0406901 0.0542535], ...
'String','to', ...
'Style','text', ...
'Tag','StaticText3');
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'Callback','uiresume(gcbf)', ...
'Position',[0.630697 0.0678168 0.12207 0.0542535], ...
'String','OK', ...
'Tag','Pushbutton1');
b = uicontrol('Parent',hndl_win, ...
'Units','normalized', ...
'Callback',[ ...
'gui_help(''pcamat'');' ...
], ...
'Position',[0.767008 0.0678168 0.12207 0.0542535], ...
'String','Help', ...
'Tag','Pushbutton2');
h_axes = axes('Position' ,[0.13 0.3 0.775 0.6]);
set(hndl_win, 'currentaxes',h_axes);
bar(eigenvalues);
title('Eigenvalues');
uiwait(hndl_win);
firstEig = str2num(get(e_first, 'String'));
lastEig = str2num(get(e_last, 'String'));
% close the window
close(hndl_win);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% See if the user has reduced the dimension enought
if lastEig > maxLastEig
lastEig = maxLastEig;
if b_verbose
fprintf('Dimension reduced to %d due to the singularity of covariance matrix\n',...
lastEig-firstEig+1);
end
else
% Reduce the dimensionality of the problem.
if b_verbose
if oldDimension == (lastEig - firstEig + 1)
fprintf ('Dimension not reduced.\n');
else
fprintf ('Reducing dimension...\n');
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Drop the smaller eigenvalues
if lastEig < oldDimension
lowerLimitValue = (eigenvalues(lastEig) + eigenvalues(lastEig + 1)) / 2;
else
lowerLimitValue = eigenvalues(oldDimension) - 1;
end
lowerColumns = diag(D) > lowerLimitValue;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Drop the larger eigenvalues
if firstEig > 1
higherLimitValue = (eigenvalues(firstEig - 1) + eigenvalues(firstEig)) / 2;
else
higherLimitValue = eigenvalues(1) + 1;
end
higherColumns = diag(D) < higherLimitValue;
% Combine the results from above
selectedColumns = lowerColumns & higherColumns;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% print some info for the user
if b_verbose
fprintf ('Selected [ %d ] dimensions.\n', sum (selectedColumns));
end
if sum (selectedColumns) ~= (lastEig - firstEig + 1),
error ('Selected a wrong number of dimensions.');
end
if b_verbose
fprintf ('Smallest remaining (non-zero) eigenvalue [ %g ]\n', eigenvalues(lastEig));
fprintf ('Largest remaining (non-zero) eigenvalue [ %g ]\n', eigenvalues(firstEig));
fprintf ('Sum of removed eigenvalues [ %g ]\n', sum(diag(D) .* ...
(~selectedColumns)));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Select the colums which correspond to the desired range
% of eigenvalues.
E = selcol(E, selectedColumns);
D = selcol(selcol(D, selectedColumns)', selectedColumns);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Some more information
if b_verbose
sumAll=sum(eigenvalues);
sumUsed=sum(diag(D));
retained = (sumUsed / sumAll) * 100;
fprintf('[ %g ] %% of (non-zero) eigenvalues retained.\n', retained);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function newMatrix = selcol(oldMatrix, maskVector);
% newMatrix = selcol(oldMatrix, maskVector);
%
% Selects the columns of the matrix that marked by one in the given vector.
% The maskVector is a column vector.
% 15.3.1998
if size(maskVector, 1) ~= size(oldMatrix, 2),
error ('The mask vector and matrix are of uncompatible size.');
end
numTaken = 0;
for i = 1 : size (maskVector, 1),
if maskVector(i, 1) == 1,
takingMask(1, numTaken + 1) = i;
numTaken = numTaken + 1;
end
end
newMatrix = oldMatrix(:, takingMask);
|
github
|
Sina-Baharlou/Face-Recognition-master
|
icaplot.m
|
.m
|
Face-Recognition-master/fica/icaplot.m
| 13,259 |
utf_8
|
dde3e6d852f657a3c1eaacbd03f5dcc7
|
function icaplot(mode, varargin);
%ICAPLOT - plot signals in various ways
%
% ICAPLOT is mainly for plottinf and comparing the mixed signals and
% separated ica-signals.
%
% ICAPLOT has many different modes. The first parameter of the function
% defines the mode. Other parameters and their order depends on the
% mode. The explanation for the more common parameters is in the end.
%
% Classic
% icaplot('classic', s1, n1, range, xrange, titlestr)
%
% Plots the signals in the same manner as the FASTICA and FASTICAG
% programs do. All the signals are plotted in their own axis.
%
% Complot
% icaplot('complot', s1, n1, range, xrange, titlestr)
%
% The signals are plotted on the same axis. This is good for
% visualization of the shape of the signals. The scale of the signals
% has been altered so that they all fit nicely.
%
% Histogram
% icaplot('histogram', s1, n1, range, bins, style)
%
% The histogram of the signals is plotted. The number of bins can be
% specified with 'bins'-parameter. The style for the histograms can
% be either 'bar' (default) of 'line'.
%
% Scatter
% icaplot('scatter', s1, n1, s2, n2, range, titlestr, s1label,
% s2label, markerstr)
%
% A scatterplot is plotted so that the signal 1 is the 'X'-variable
% and the signal 2 is the 'Y'-variable. The 'markerstr' can be used
% to specify the maker used in the plot. The format for 'markerstr'
% is the same as for Matlab's PLOT.
%
% Compare
% icaplot('compare', s1, n1, s2, n2, range, xrange, titlestr,
% s1label, s2label)
%
% This for for comparing two signals. The main used in this context
% would probably be to see how well the separated ICA-signals explain
% the observed mixed signals. The s2 signals are first scaled with
% REGRESS function.
%
% Compare - Sum
% icaplot('sum', s1, n1, s2, n2, range, xrange, titlestr, s1label,
% s2label)
%
% The same as Compare, but this time the signals in s2 (specified by
% n2) are summed together.
%
% Compare - Sumerror
% icaplot('sumerror', s1, n1, s2, n2, range, xrange, titlestr,
% s1label, s2label)
%
% The same as Compare - Sum, but also the 'error' between the signal
% 1 and the summed IC's is plotted.
%
%
% More common parameters
% The signals to be plotted are in matrices s1 and s2. The n1 and n2
% are used to tell the index of the signal or signals to be plotted
% from s1 or s2. If n1 or n2 has a value of 0, then all the signals
% from corresponding matrix will be plotted. The values for n1 and n2
% can also be vectors (like: [1 3 4]) In some casee if there are more
% than 1 signal to be plotted from s1 or s2 then the plot will
% contain as many subplots as are needed.
%
% The range of the signals to be plotted can be limited with
% 'range'-parameter. It's value is a vector ( 10000:15000 ). If range
% is 0, then the whole range will be plotted.
%
% The 'xrange' is used to specify only the labels used on the
% x-axis. The value of 'xrange' is a vector containing the x-values
% for the plots or [start end] for begin and end of the range
% ( 10000:15000 or [10 15] ). If xrange is 0, then value of range
% will be used for x-labels.
%
% You can give a title for the plot with 'titlestr'. Also the
% 's1label' and 's2label' are used to give more meaningfull label for
% the signals.
%
% Lastly, you can omit some of the arguments from the and. You will
% have to give values for the signal matrices (s1, s2) and the
% indexes (n1, n2)
% @(#)$Id: icaplot.m,v 1.2 2003/04/05 14:23:58 jarmo Exp $
switch mode
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 'dispsig' is to replace the old DISPSIG
% '' & 'classic' are just another names - '' quite short one :-)
case {'', 'classic', 'dispsig'}
% icaplot(mode, s1, n1, range, xrange, titlestr)
if length(varargin) < 1, error('Not enough arguments.'); end
if length(varargin) < 5, titlestr = '';else titlestr = varargin{5}; end
if length(varargin) < 4, xrange = 0;else xrange = varargin{4}; end
if length(varargin) < 3, range = 0;else range = varargin{3}; end
if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end
s1 = varargin{1};
range=chkrange(range, s1);
xrange=chkxrange(xrange, range);
n1=chkn(n1, s1);
clf;
numSignals = size(n1, 2);
for i = 1:numSignals,
subplot(numSignals, 1, i);
plot(xrange, s1(n1(i), range));
end
subplot(numSignals,1, 1);
if (~isempty(titlestr))
title(titlestr);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'complot'
% icaplot(mode, s1, n1, range, xrange, titlestr)
if length(varargin) < 1, error('Not enough arguments.'); end
if length(varargin) < 5, titlestr = '';else titlestr = varargin{5}; end
if length(varargin) < 4, xrange = 0;else xrange = varargin{4}; end
if length(varargin) < 3, range = 0;else range = varargin{3}; end
if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end
s1 = remmean(varargin{1});
range=chkrange(range, s1);
xrange=chkxrange(xrange, range);
n1=chkn(n1, s1);
for i = 1:size(n1, 2)
S1(i, :) = s1(n1(i), range);
end
alpha = mean(max(S1')-min(S1'));
for i = 1:size(n1,2)
S2(i,:) = S1(i,:) - alpha*(i-1)*ones(size(S1(1,:)));
end
plot(xrange, S2');
axis([min(xrange) max(xrange) min(min(S2)) max(max(S2)) ]);
set(gca,'YTick',(-size(S1,1)+1)*alpha:alpha:0);
set(gca,'YTicklabel',fliplr(n1));
if (~isempty(titlestr))
title(titlestr);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'histogram'
% icaplot(mode, s1, n1, range, bins, style)
if length(varargin) < 1, error('Not enough arguments.'); end
if length(varargin) < 5, style = 'bar';else style = varargin{5}; end
if length(varargin) < 4, bins = 10;else bins = varargin{4}; end
if length(varargin) < 3, range = 0;else range = varargin{3}; end
if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end
s1 = varargin{1};
range = chkrange(range, s1);
n1 = chkn(n1, s1);
numSignals = size(n1, 2);
rows = floor(sqrt(numSignals));
columns = ceil(sqrt(numSignals));
while (rows * columns < numSignals)
columns = columns + 1;
end
switch style
case {'', 'bar'}
for i = 1:numSignals,
subplot(rows, columns, i);
hist(s1(n1(i), range), bins);
title(int2str(n1(i)));
drawnow;
end
case 'line'
for i = 1:numSignals,
subplot(rows, columns, i);
[Y, X]=hist(s1(n1(i), range), bins);
plot(X, Y);
title(int2str(n1(i)));
drawnow;
end
otherwise
fprintf('Unknown style.\n')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'scatter'
% icaplot(mode, s1, n1, s2, n2, range, titlestr, xlabelstr, ylabelstr, markerstr)
if length(varargin) < 4, error('Not enough arguments.'); end
if length(varargin) < 9, markerstr = '.';else markerstr = varargin{9}; end
if length(varargin) < 8, ylabelstr = 'Signal 2';else ylabelstr = varargin{8}; end
if length(varargin) < 7, xlabelstr = 'Signal 1';else xlabelstr = varargin{7}; end
if length(varargin) < 6, titlestr = '';else titlestr = varargin{6}; end
if length(varargin) < 5, range = 0;else range = varargin{5}; end
n2 = varargin{4};
s2 = varargin{3};
n1 = varargin{2};
s1 = varargin{1};
range = chkrange(range, s1);
n1 = chkn(n1, s1);
n2 = chkn(n2, s2);
rows = size(n1, 2);
columns = size(n2, 2);
for r = 1:rows
for c = 1:columns
subplot(rows, columns, (r-1)*columns + c);
plot(s1(n1(r), range),s2(n2(c), range),markerstr);
if (~isempty(titlestr))
title(titlestr);
end
if (rows*columns == 1)
xlabel(xlabelstr);
ylabel(ylabelstr);
else
xlabel([xlabelstr ' (' int2str(n1(r)) ')']);
ylabel([ylabelstr ' (' int2str(n2(c)) ')']);
end
drawnow;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case {'compare', 'sum', 'sumerror'}
% icaplot(mode, s1, n1, s2, n2, range, xrange, titlestr, s1label, s2label)
if length(varargin) < 4, error('Not enough arguments.'); end
if length(varargin) < 9, s2label = 'IC';else s2label = varargin{9}; end
if length(varargin) < 8, s1label = 'Mix';else s1label = varargin{8}; end
if length(varargin) < 7, titlestr = '';else titlestr = varargin{7}; end
if length(varargin) < 6, xrange = 0;else xrange = varargin{6}; end
if length(varargin) < 5, range = 0;else range = varargin{5}; end
s1 = varargin{1};
n1 = varargin{2};
s2 = varargin{3};
n2 = varargin{4};
range = chkrange(range, s1);
xrange = chkxrange(xrange, range);
n1 = chkn(n1, s1);
n2 = chkn(n2, s2);
numSignals = size(n1, 2);
if (numSignals > 1)
externalLegend = 1;
else
externalLegend = 0;
end
rows = floor(sqrt(numSignals+externalLegend));
columns = ceil(sqrt(numSignals+externalLegend));
while (rows * columns < (numSignals+externalLegend))
columns = columns + 1;
end
clf;
for j = 1:numSignals
subplot(rows, columns, j);
switch mode
case 'compare'
plotcompare(s1, n1(j), s2,n2, range, xrange);
[legendtext,legendstyle]=legendcompare(n1(j),n2,s1label,s2label,externalLegend);
case 'sum'
plotsum(s1, n1(j), s2,n2, range, xrange);
[legendtext,legendstyle]=legendsum(n1(j),n2,s1label,s2label,externalLegend);
case 'sumerror'
plotsumerror(s1, n1(j), s2,n2, range, xrange);
[legendtext,legendstyle]=legendsumerror(n1(j),n2,s1label,s2label,externalLegend);
end
if externalLegend
title([titlestr ' (' s1label ' ' int2str(n1(j)) ')']);
else
legend(char(legendtext));
if (~isempty(titlestr))
title(titlestr);
end
end
end
if (externalLegend)
subplot(rows, columns, numSignals+1);
legendsize = size(legendtext, 2);
hold on;
for i=1:legendsize
plot([0 1],[legendsize-i legendsize-i], char(legendstyle(i)));
text(1.5, legendsize-i, char(legendtext(i)));
end
hold off;
axis([0 6 -1 legendsize]);
axis off;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotcompare(s1, n1, s2, n2, range, xrange);
style=getStyles;
K = regress(s1(n1,:)',s2');
plot(xrange, s1(n1,range), char(style(1)));
hold on
for i=1:size(n2,2)
plotstyle=char(style(i+1));
plot(xrange, K(n2(i))*s2(n2(i),range), plotstyle);
end
hold off
function [legendText, legendStyle]=legendcompare(n1, n2, s1l, s2l, externalLegend);
style=getStyles;
if (externalLegend)
legendText(1)={[s1l ' (see the titles)']};
else
legendText(1)={[s1l ' ', int2str(n1)]};
end
legendStyle(1)=style(1);
for i=1:size(n2, 2)
legendText(i+1) = {[s2l ' ' int2str(n2(i))]};
legendStyle(i+1) = style(i+1);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotsum(s1, n1, s2, n2, range, xrange);
K = diag(regress(s1(n1,:)',s2'));
sigsum = sum(K(:,n2)*s2(n2,:));
plot(xrange, s1(n1, range),'k-', ...
xrange, sigsum(range), 'b-');
function [legendText, legendStyle]=legendsum(n1, n2, s1l, s2l, externalLegend);
if (externalLegend)
legendText(1)={[s1l ' (see the titles)']};
else
legendText(1)={[s1l ' ', int2str(n1)]};
end
legendText(2)={['Sum of ' s2l ': ', int2str(n2)]};
legendStyle={'k-';'b-'};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotsumerror(s1, n1, s2, n2, range, xrange);
K = diag(regress(s1(n1,:)',s2'));
sigsum = sum(K(:,n2)*s2(n2,:));
plot(xrange, s1(n1, range),'k-', ...
xrange, sigsum(range), 'b-', ...
xrange, s1(n1, range)-sigsum(range), 'r-');
function [legendText, legendStyle]=legendsumerror(n1, n2, s1l, s2l, externalLegend);
if (externalLegend)
legendText(1)={[s1l ' (see the titles)']};
else
legendText(1)={[s1l ' ', int2str(n1)]};
end
legendText(2)={['Sum of ' s2l ': ', int2str(n2)]};
legendText(3)={'"Error"'};
legendStyle={'k-';'b-';'r-'};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function style=getStyles;
color = {'k','r','g','b','m','c','y'};
line = {'-',':','-.','--'};
for i = 0:size(line,2)-1
for j = 1:size(color, 2)
style(j + i*size(color, 2)) = strcat(color(j), line(i+1));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function range=chkrange(r, s)
if r == 0
range = 1:size(s, 2);
else
range = r;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xrange=chkxrange(xr,r);
if xr == 0
xrange = r;
elseif size(xr, 2) == 2
xrange = xr(1):(xr(2)-xr(1))/(size(r,2)-1):xr(2);
elseif size(xr, 2)~=size(r, 2)
error('Xrange and range have different sizes.');
else
xrange = xr;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function n=chkn(n,s)
if n == 0
n = 1:size(s, 1);
end
|
github
|
FateNozomi/sign_language_recognition-master
|
kinect_gui.m
|
.m
|
sign_language_recognition-master/kinect_gui.m
| 13,798 |
utf_8
|
f565b17e03f7f311899be07087df0c6e
|
function varargout = kinect_gui(varargin)
% KINECT_GUI MATLAB code for kinect_gui.fig
% KINECT_GUI, by itself, creates a new KINECT_GUI or raises the existing
% singleton*.
%
% H = KINECT_GUI returns the handle to a new KINECT_GUI or the handle to
% the existing singleton*.
%
% KINECT_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in KINECT_GUI.M with the given input arguments.
%
% KINECT_GUI('Property','Value',...) creates a new KINECT_GUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before kinect_gui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to kinect_gui_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help kinect_gui
% Last Modified by GUIDE v2.5 09-Sep-2016 00:18:37
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @kinect_gui_OpeningFcn, ...
'gui_OutputFcn', @kinect_gui_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before kinect_gui is made visible.
function kinect_gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to kinect_gui (see VARARGIN)
axes(handles.kinect_axes);
% initialize kinect RGB input
info = imaqhwinfo('kinect');
if isempty(info.DeviceInfo) ~= 1
colorVid = videoinput('kinect',1,'RGB_640x480');
% Create an image object for previewing.
% http://www.mathworks.com/help/imaq/preview.html
% Use get(colorVid) to view a complete list of all the properties
% supported by a video input object or a video source object
% VideoResolution of colorVid returns an array of [640 480]
% vidRes(2) returns the height of colorVid
% vidRes(1) returns the width of colorVid
% nBands returns number of color bands in data to be acquired
vidRes = colorVid.VideoResolution;
nBands = colorVid.NumberOfBands;
% create placeholder image which matches source
hImage = image( zeros(vidRes(2), vidRes(1), nBands) );
preview(colorVid, hImage);
end
axes(handles.sign_axes);
asl_preview_directory = [pwd '\asl_preview'];
% Select files using a specified pattern
filePattern = fullfile(asl_preview_directory, '*.png');
% Lists out all required files which follows the pattern
reqFiles = dir(filePattern);
for k = 1 : length(reqFiles)
%Index into the structure to access a particular item from reqFiles
baseFileName = reqFiles(k).name;
%fullfile returns a string containing the full path to the file
baseFilePath = fullfile(asl_preview_directory, baseFileName);
fprintf(1, 'Accessing %s\n', baseFilePath);
%Create cell array S of size() [2,K]
%Fills up first row of S with length(reqFiles)
handles.S{1,k} = k;
%Fills up second row of S imread(baseFilePath)
handles.S{2,k} = imread(baseFilePath);
end
% converts cell to matrix in order to imshow
handles.signA = imshow(cell2mat(handles.S(2,1)));
handles.current_sign = handles.signA;
% Choose default command line output for kinect_gui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes kinect_gui wait for user response (see UIRESUME)
% uiwait(handles.kinect_gui);
% --- Outputs from this function are returned to the command line.
function varargout = kinect_gui_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on selection change in alphabet_popupmenu.
function alphabet_popupmenu_Callback(hObject, eventdata, handles)
% hObject handle to alphabet_popupmenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns alphabet_popupmenu contents as cell array
% contents{get(hObject,'Value')} returns selected item from alphabet_popupmenu
val = get(hObject, 'Value');
str = get(hObject, 'String');
switch str{val}
case 'A'
handles.signA = imshow(cell2mat(handles.S(2,1)));
handles.current_sign = handles.signA;
case 'B'
handles.signB = imshow(cell2mat(handles.S(2,2)));
handles.current_sign = handles.signB;
case 'C'
handles.signC = imshow(cell2mat(handles.S(2,3)));
handles.current_sign = handles.signC;
case 'D'
handles.signD = imshow(cell2mat(handles.S(2,4)));
handles.current_sign = handles.signD;
case 'E'
handles.signE = imshow(cell2mat(handles.S(2,5)));
handles.current_sign = handles.signE;
case 'F'
handles.signF = imshow(cell2mat(handles.S(2,6)));
handles.current_sign = handles.signF;
case 'G'
handles.signG = imshow(cell2mat(handles.S(2,7)));
handles.current_sign = handles.signG;
case 'H'
handles.signH = imshow(cell2mat(handles.S(2,8)));
handles.current_sign = handles.signH;
case 'I'
handles.signI = imshow(cell2mat(handles.S(2,9)));
handles.current_sign = handles.signI;
case 'K'
handles.signK = imshow(cell2mat(handles.S(2,11)));
handles.current_sign = handles.signK;
case 'L'
handles.signL = imshow(cell2mat(handles.S(2,12)));
handles.current_sign = handles.signL;
case 'M'
handles.signM = imshow(cell2mat(handles.S(2,13)));
handles.current_sign = handles.signM;
case 'N'
handles.signN = imshow(cell2mat(handles.S(2,14)));
handles.current_sign = handles.signN;
case 'O'
handles.signO = imshow(cell2mat(handles.S(2,15)));
handles.current_sign = handles.signO;
case 'P'
handles.signP = imshow(cell2mat(handles.S(2,16)));
handles.current_sign = handles.signP;
case 'Q'
handles.signQ = imshow(cell2mat(handles.S(2,17)));
handles.current_sign = handles.signQ;
case 'R'
handles.signR = imshow(cell2mat(handles.S(2,18)));
handles.current_sign = handles.signR;
case 'S'
handles.signS = imshow(cell2mat(handles.S(2,19)));
handles.current_sign = handles.signS;
case 'T'
handles.signT = imshow(cell2mat(handles.S(2,20)));
handles.current_sign = handles.signT;
case 'U'
handles.signU = imshow(cell2mat(handles.S(2,21)));
handles.current_sign = handles.signU;
case 'V'
handles.signV = imshow(cell2mat(handles.S(2,22)));
handles.current_sign = handles.signV;
case 'W'
handles.signW = imshow(cell2mat(handles.S(2,23)));
handles.current_sign = handles.signW;
case 'X'
handles.signX = imshow(cell2mat(handles.S(2,24)));
handles.current_sign = handles.signX;
case 'Y'
handles.signY = imshow(cell2mat(handles.S(2,25)));
handles.current_sign = handles.signY;
end
% Update handles structure
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function alphabet_popupmenu_CreateFcn(hObject, eventdata, handles)
% hObject handle to alphabet_popupmenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu 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 check_sign_pushbutton.
function check_sign_pushbutton_Callback(hObject, eventdata, handles)
% hObject handle to check_sign_pushbutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.output_text, 'String', 'Analyzing');
S = PCA_v2_Kinect_Input_fcn;
switch handles.current_sign
case handles.signA
if S == 'A'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signB
if S == 'B'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signC
if S == 'C'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signD
if S == 'D'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signE
if S == 'E'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signF
if S == 'F'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signG
if S == 'G'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signH
if S == 'H'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signI
if S == 'I'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signK
if S == 'K'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signL
if S == 'L'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signM
if S == 'M'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signN
if S == 'N'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signO
if S == 'O'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signP
if S == 'P'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signQ
if S == 'Q'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signR
if S == 'R'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signS
if S == 'S'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signT
if S == 'T'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signU
if S == 'U'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signV
if S == 'V'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signW
if S == 'W'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signX
if S == 'X'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
case handles.signY
if S == 'Y'
set(handles.output_text, 'String', 'Correct');
else
set(handles.output_text, 'String', 'Wrong');
end
end
% --- Executes when user attempts to close kinect_gui.
function kinect_gui_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to kinect_gui (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: delete(hObject) closes the figure
delete(hObject);
|
github
|
ionefine/retinotopic-mapping-master
|
doSimonScotoma2color.m
|
.m
|
retinotopic-mapping-master/doSimonScotoma2color.m
| 9,571 |
utf_8
|
780f6dc3c0fa388d0e08637ba1c402c1
|
function task=doSimonScotoma2color(display,task,curTime)
%s=doSimon(display,s,curTime)
escPressed=0;
switch task.action
case 'init' %set up simon variables
% 'simon' parameters
if ~isfield(task, 'scFac')
task.scFac=1;
end
task.size = angle2pix(display, task.apertures); %pixels
task.gap = 2; %pixels
task.c = ceil(display.resolution/2)+task.fixoffset;
for i=1:length(task.size)
task.rect{i} = [-task.size(i)/2+task.c(1),-task.size(i)/2+task.c(2),+task.size(i)/2+task.c(1),+task.size(i)/2+task.c(2)];
end
task.color{1} = [0,0,255];
task.color{2} = [255,255,0];
task.color{3} = [0,255,0];
task.color{4} = [255,0,0];
task.seq = [];
task.maxLen = [];
task.i = 0;
task.state = 'off';
task.seq = task.goodKeys(ceil(rand(1)*length(task.goodKeys)));
task.pauseTill = 1;
task.action = 'play';
task.event.type = 'switch to play';
task.event.time = 0;
task.event.num = 0;
task.numEvents = 1;
showSimon(display,task);
case 'play' %sequence playback mode
if task.pauseTill < curTime
t = mod(curTime,task.ISI);
if strcmp(task.state,'off') && t<=task.dur
task.i = task.i+1;
if task.i<=length(task.seq);
task.show = task.seq(task.i);
task.state = 'on';
task.numEvents = task.numEvents+1;
task.event(task.numEvents).type= 'play: on';
task.event(task.numEvents).time = curTime;
task.event(task.numEvents).num = task.show;
else
task.numEvents = task.numEvents+1;
task.event(task.numEvents).type= 'switch to recall';
task.event(task.numEvents).time = curTime;
task.event(task.numEvents).num = NaN;
task.action = 'recall';
task.state = 'off';
task.i = 0;
end
elseif strcmp(task.state,'on') && t> task.dur
task.numEvents = task.numEvents+1;
task.event(task.numEvents).type= 'play: off';
task.event(task.numEvents).time = curTime;
task.event(task.numEvents).num = task.show;
task.state = 'off';
end
end
showSimon(display,task);
case 'recall'
if task.pauseTill<curTime
%see if a key is pressed
[ keyIsDown, timeSecs, keyCode ] = KbCheck;
if keyIsDown && strcmp(task.state,'off') %a key is down: record the key and time pressed
keyPressed= KbName(keyCode);
keyNum = find(strcmp(keyPressed(1),task.keys));
if ~isempty(keyNum)
task.show = keyNum;
task.state = 'on';
task.numEvents = task.numEvents+1;
task.event(task.numEvents).type= 'recall: on';
task.event(task.numEvents).time = curTime;
task.event(task.numEvents).num = task.show;
end
elseif ~keyIsDown && strcmp(task.state,'on') %key just lifted
task.state = 'off';
task.numEvents = task.numEvents+1;
task.event(task.numEvents).type= 'recall: off';
task.event(task.numEvents).time = curTime;
task.event(task.numEvents).num = NaN;
task.i = task.i+1;
if task.show ~= task.seq(task.i)
%incorrect
task.maxLen = [task.maxLen,length(task.seq)-1];
task.pauseTill = ceil(curTime+ task.errDur);
task.action = 'error';
task.numEvents = task.numEvents+1;
task.event(task.numEvents).type= 'error: start';
task.event(task.numEvents).time = curTime;
task.event(task.numEvents).num = task.seq(end);
elseif task.i == length(task.seq) %got the last one right
task.seq = [task.seq,task.goodKeys(ceil(rand(1)*length(task.goodKeys)))];
task.state = 'off';
task.action = 'play';
task.i = 0;
task.pauseTill = ceil(curTime+ task.pauseDur) ;
task.numEvents = task.numEvents+1;
task.event(task.numEvents).type= 'switch to play';
task.event(task.numEvents).time = curTime;
task.event(task.numEvents).num = NaN;
end
end
end
showSimon(display,task);
case 'error'
if curTime < task.pauseTill
ab = mod(curTime*task.errFreq,1);
task.show = task.seq(end);
if ab<.5
task.state = 'on';
else
task.state = 'off';
end
showSimon(display,task);
else
task.i = 0;
task.seq = task.goodKeys(ceil(rand(1)*length(task.goodKeys)));
task.action = 'play';
task.state = 'off';
task.pauseTill = ceil(curTime+ task.pauseDur);
task.numEvents = task.numEvents+1;
task.event(task.numEvents).type= 'error: stop';
task.event(task.numEvents).time = curTime;
task.event(task.numEvents).num = NaN;
end
case 'done'
task.maxLen = [task.maxLen,length(task.seq)-1];
task.numEvents = task.numEvents+1;
task.event(task.numEvents).type= 'done';
task.event(task.numEvents).time = curTime;
task.event(task.numEvents).num = NaN;
task.seq = [];
end
end
function showSimon(display,task)
task.c = ceil(display.resolution/2)+task.fixoffset;
for i=1:length(task.size)
task.rect{i} = [-task.size(i)/2+task.c(1),-task.size(i)/2+task.c(2),+task.size(i)/2+task.c(1),+task.size(i)/2+task.c(2)];
end
switch task.state
case 'on';
Screen('FillOval',display.windowPtr,[100,100,100],task.rect{3});
if strcmp(task.action, 'error')
Screen('FillArc',display.windowPtr,[ 0 0 0 ],task.rect{2},180*(task.show-1)+task.rotAng,180);
else
Screen('FillArc',display.windowPtr,task.color{task.show},task.rect{2},180*(task.show-1)+task.rotAng,180);
end
Screen('FillOval',display.windowPtr,[128,128,128],task.rect{1});
Screen('FillOval',display.windowPtr,[255,255,255],task.rect{4});
if task.rotAng==0
Screen('FillRect',display.windowPtr,[128,128,128],[task.c(1)-task.gap/2,task.c(2)-task.size(2)/2,task.c(1)+task.gap/2,task.c(2)+task.size(2)/2]);
elseif task.rotAng==-45
Screen('DrawLine',display.windowPtr, [128,128,128], ...
task.c(1)-(.75*task.size(2))/2, task.c(2)-(.75*task.size(2))/2, ...
task.c(1)+(.75*task.size(2))/2 , task.c(2)+(.75*task.size(2))/2, min([task.scFac 4]));
elseif task.rotAng==45
Screen('DrawLine',display.windowPtr, [128,128,128], ...
task.c(1)-(.75*task.size(2))/2, task.c(2)+(.75*task.size(2))/2 , ...
task.c(1)+(.75*task.size(2))/2 , task.c(2)-(.75*task.size(2))/2, min([task.scFac 4]));
elseif task.rotAng==90
Screen('FillRect',display.windowPtr,[128,128,128],[task.c(1)-task.size(2)/2,task.c(2)-task.gap/2,task.c(1)+task.size(2)/2,task.c(2)+task.gap/2]);
end
case 'off'
Screen('FillOval',display.windowPtr,[100,100,100],task.rect{3});
Screen('FillOval',display.windowPtr,[128,128,128],task.rect{1});
Screen('FillOval',display.windowPtr,[255,255,255],task.rect{4});
if task.rotAng==0
Screen('FillRect',display.windowPtr,[128,128,128],[task.c(1)-task.gap/2,task.c(2)-task.size(2)/2,task.c(1)+task.gap/2,task.c(2)+task.size(2)/2]);
elseif task.rotAng==-45
Screen('DrawLine',display.windowPtr, [128,128,128], ...
task.c(1)-(.75*task.size(2))/2, task.c(2)-(.75*task.size(2))/2, ...
task.c(1)+(.75*task.size(2))/2 , task.c(2)+(.75*task.size(2))/2, min([task.scFac 4]));
elseif task.rotAng==45
Screen('DrawLine',display.windowPtr, [128,128,128], ...
task.c(1)-(.75*task.size(2))/2, task.c(2)+(.75*task.size(2))/2 , ...
task.c(1)+(.75*task.size(2))/2 , task.c(2)-(.75*task.size(2))/2, min([task.scFac 4]));
elseif task.rotAng==90
Screen('FillRect',display.windowPtr,[128,128,128],[task.c(1)-task.size(2)/2,task.c(2)-task.gap/2,task.c(1)+task.size(2)/2,task.c(2)+task.gap/2]);
end
otherwise
disp(sprintf('state %s not recognized',task.state));
end
end
|
github
|
ionefine/retinotopic-mapping-master
|
RetinotopyMain.m
|
.m
|
retinotopic-mapping-master/RetinotopyMain.m
| 14,348 |
utf_8
|
0e5302c43a01b6f8269cd45f701fd505
|
function [stim, eye, display]=RetinotopyMain(subjID, typeID, scanID)
% subjID='JMD1';
% typeID='bar'
% scanID='1';
close all hidden
place='Ione';
if strcmp(place, 'Ione')
homedir =[ 'C:' filesep 'Users' filesep 'Ione Fine' filesep 'Documents' filesep ...
'Work' filesep 'Science' filesep 'Projects' filesep 'Ione Fine' filesep '\retinotopic-mapping'];
elseif strcmp(place, 'You');
homedir='what you want here';
end
cd(homedir);
rng('default'); rng(sum(100*clock)); stim.seed=rng; % saves the random seed in case you want to recreate the scan
stim.filename=[subjID, '_',typeID, '_', num2str(scanID)];
%% screen variables and trigger key
display.dist = 36.5; %distance from screen (cm)
display.width = 27.5; %width of screen (cm)
display.screenNum = 0;
display.skipChecks = 1;
display.bkColor = [0 0 0];
display.gamma = 0:255;% This is if the monitor is linear!!
% open and close the display in order to set some more generic display parameters
display = OpenWindow(display);
display.rect = Screen('Rect', display.windowPtr);
Screen('CloseAll');
display.screenAngle = pix2angle( display, display.resolution(1));
display.blankImg = 128*ones(display.rect(4), display.rect(3));
%% stimulus parameters, timing
% To alter other aspects of the stimuli go into MakeStimulus
stim.triggerKey = '5'; %key code for starting the scanner
stim.dur = 30; %duration of scan (seconds)
if stim.dur<30 && strcmp(typeID, 'mf')
error('Multifocal will produce weird segment orders if not adequate duration');
end
stim.type=typeID; %'mf' or 'bar'
stim.logscaled=1; % determines whether eccentricity rings are log scaled to match cortical expansion
stim.expFac=1.2; %scales the virtual screen to to be larger than real screen. Can be 1 for real patients.
% If simulating eye-movements needs to be proportional to the size of the
% eye-movements
if strcmp(stim.type, 'mf')
stim.hz=1/3; % the rate at which mf stimulus updates
% number of positions the bar/mf stimulus takes
elseif strcmp(stim.type, 'bar')
stim.hz=8;% the rate for the updating of the bar, convenient to set it to match the background flicker rate
end
stim.npos = ceil(stim.dur/(1./stim.hz));
stim.switchtime=0:(1/stim.hz):stim.dur;
%% calculate some generic parameters relating the stimulus to the display screen
[stim.X,stim.Y] = meshgrid(linspace(-1,1,display.resolution(1)*stim.expFac));
stim.XDeg=stim.X.*display.screenAngle*stim.expFac/2;
stim.YDeg=stim.Y.*display.screenAngle*stim.expFac/2;
stim.RDeg=sqrt(stim.XDeg.^2+stim.YDeg.^2);
stim.T=atan2(stim.Y,stim.X)./pi; % angular rotation
stim.rect=CenterRect([1 1 display.resolution(1) display.resolution(2)],[ 1 1 size(stim.X)]);
%% eye-movements
% modeling two types of eye-movements, slow drift and jitter
% for a real patient you want everything fixed (0)
eye.jitter.move=0; % this jitters the stimulus while keeping fix fixed, good for mimicking small rapid movements
% 0 - no jitter, 1- instability based on Bethlehem, Dumoulin, Dalmaijer, et al. Decreased Fixation Stability of the Preferred Retinal Location in Juvenile Macular Degeneration. Baker CI, ed. PLoS ONE. 2014;9(6)
eye.drift.move=[0 0; 0 0];% [4, 5; 6 3]; % this moves the fixation spot, good for big slow eye-movments.
% First row describes x, y drift distance (in degrees). Second row
% descripes the oscillation rate in degrees/seconds
eye.frameRate=display.frameRate;
if eye.jitter.move+sum(eye.drift.move(1,:))>0 && stim.expFac==1;
error('stim.expFac must be greater than 1 to allow for eye-movements');
end
[eye, stim]=SimulateEyeMovements(eye, stim);
%% fixation parameters
fix.offset=[0 0]; %location of the fixation spot in the display, x y degrees for - +ve x y values the fix spot moves to the left or to the upper part of the screen
fix.scFac=8; % size of the fix spot, 1 is the default
%% background
stim.background.nsectors=18; % controls how fine the background texture is, should be finer scale than the mf stimulus
stim.background.nrings=40;
stim.background.n=3; % how many jitter positions for the texture
stim.background.hz=8; % rate at which the background flickers
stim.background.switchtime=0:(1/stim.background.hz):stim.dur;
if stim.background.hz<stim.hz
error('Background must update at the same or faster rate than stimulus')
end
stim=MakeBackground(stim);
%% scotoma
stim.scotoma.rad = 1;
stim.scotoma.center = [0 0]; % x, y in degrees
% for - positive x y values the fix spot moves to the left or to the upper part of the screen
if stim.scotoma.rad>0
stim=MakeScotoma(stim);
else
stim.scotoma.img=ones(size(stim.X));
end
if strcmp(stim.type, 'bar')
stim.bar.speed = [2,3]; %speed range degrees/sec
stim.bar.width=6;
stim=MakeBar(stim);
elseif strcmp(stim.type, 'mf')
stim.mf.nrings=8; % total number of rings
stim.mf.inner=.25; % radius of the inner ring
stim.mf.sectors=12; % number of angular sectors
stim.mf.nrot=1; % number of times and direction it rotates back and forth the angular width of a segment in the scan
stim.mf.nEC=3; % number of times it expands and contracts
stim.mf.noneighbors=0; %neigborFlag flag to determine if neighbors cannot be on at the same time
stim=MakeMF(stim);
end
%try
display = OpenWindow(display); HideCursor;
%% initialize Simon task
task.apertures=[1,3,3.3,.1]; % inner edge of the segments, outer edge of segments, outer edge, inner hole
task.action = 'init'; task.fixoffset=round(angle2pix(display, fix.offset)/2);
task.rotAng=45; % can be 0 (vert), -45 , 45 (diag, pointing towards fix) or 90 (horiz)
task.ISI = 1/3; %seconds
task.dur = .25; %seconds
task.pauseDur = .25; %seconds
task.errDur = 1; %seconds
task.errFreq = 4; %Hz
task.keys = {'1' '2','3' '4'};
task.goodKeys = [1:4];
task= doSimonScotoma2color(display,task);
task.rectInit=task.rect; task.cInit=task.c; % this is the 'center' eye-position
stimflipNum=1; % keeps track of stimulus flips
backflipNum=1; on=1;% keeps track of background flips and sign
t = stim.background.switchtime; % keeps track of when to switch the stimulus
startTime = GetSecs; %read the clock
for fN=1:length(t)
curTime = GetSecs-startTime;
if curTime>stim.switchtime(1) % this decides whether to update the stimulus
stim.switchtime=stim.switchtime(2:end);
stimflipNum=mod(stimflipNum,size(stim.img, 3)-1)+1;
end
if on
backimg=stim.background.img(:,:,mod(backflipNum, size(stim.background.img, 3))+1).*255; on=0;
else
backimg=(~stim.background.img(:,:,mod(backflipNum, size(stim.background.img, 3))+1)).*255; on=1;
end
% decide what part of the stimulus/scotoma to sample from, given the eye-position of the subject,
% includes jitter but not drift, this is for the stimulus and background
rect(1,:)=stim.rect-angle2pix(display, [eye.jitter.pos(fN,1) eye.jitter.pos(fN,2) eye.jitter.pos(fN,1) eye.jitter.pos(fN,2)]);
% includes drift but not jitter, this is for the scotoma
rect(2,:)=stim.rect-angle2pix(display, [eye.drift.pos(fN,1) eye.drift.pos(fN,2) eye.drift.pos(fN,1) eye.drift.pos(fN,2)]);
img=squeeze(double(stim.img(rect(1, 2):rect(1, 4), rect(1, 1):rect(1, 3), stimflipNum))) .* ...
squeeze(backimg(rect(1, 2):rect(1, 4), rect(1, 1):rect(1, 3))) .* ...
squeeze(stim.scotoma.img(rect(2, 2):rect(2, 4), rect(2, 1):rect(2, 3)));
img = img(1:end-1,1:end-1);
% do the simon task
task.fixoffset=angle2pix(display, fix.offset)/2+angle2pix(display, eye.drift.pos(fN,:));
textureIndex=Screen('MakeTexture', display.windowPtr, img);
Screen('DrawTexture', display.windowPtr, textureIndex, display.rect);
task=doSimonScotoma2color(display,task,curTime);
Screen('Flip', display.windowPtr);
% s.fixoffset=fix.offsetP+eye.drift.posP(fN,:);
end
% catch ME
% Screen('CloseAll');
% ListenChar(0);
% ShowCursor;
% end
Screen('CloseAll');
ListenChar(0);
ShowCursor;
end
function stim=MakeBackground(stim)
if stim.logscaled==1
stim.background.ringpos=exp(linspace(.0001, log(max(stim.XDeg(:))*1.2),stim.background.nrings+1));
else
stim.background.ringpos=linspace(.0001, max(stim.XDeg(:))*1.2, stim.background.nrings+1);
end
stim.background.img=zeros([size(stim.XDeg), stim.background.n.^2]);
disp('Generating background ...');
bNum=1;
for rh=1:stim.background.n % for each radial background jitter
rings=zeros(size(stim.XDeg));
for i=1:length(stim.background.ringpos)-1; % fill in each ring
offset=rh*(diff(stim.background.ringpos(i:i+1))./stim.background.n);
rings(stim.RDeg>stim.background.ringpos(i)+offset & stim.RDeg<=stim.background.ringpos(i+1)+offset)=i;
end
for th=1:stim.background.n % for each angular jitter position of the background
segs=zeros(size(stim.XDeg));
segs(mod(stim.T*stim.background.nsectors+(th*1/stim.background.n), 1)>0.5)=1;
stim.background.img(:, :, bNum)=mod(rings+segs, 2)==0;
bNum=bNum+1;
end
end
end
function [eye, stim]=SimulateEyeMovements(eye, stim)
eye.nFrames=ceil((stim.dur*eye.frameRate)+50); % guess at how many frames will be required
if eye.jitter.move==0;
eye.jitter.pos=zeros(eye.nFrames, 2);
elseif eye.jitter.move==1 % estimated instability based on
% Bethlehem, Dumoulin, Dalmaijer, et al. Decreased Fixation Stability of the Preferred Retinal Location in Juvenile Macular Degeneration. Baker CI, ed. PLoS ONE. 2014;9(6)
eye.jitter.pos(:, 1)=linspace(0, .5,eye.nFrames)+.25.*(randn(1, eye.nFrames)); % in degrees
eye.jitter.pos(:, 2)=linspace(0, -.5,eye.nFrames)+.25.*(randn(1, eye.nFrames));
end
if sum(eye.drift.move(1, :))==0
eye.drift.pos=zeros(eye.nFrames, 2);
else
eye.drift.pos(:, 1)=eye.drift.move(1,1)*sin(linspace(0, eye.drift.move(2, 1)*pi,eye.nFrames)+.25); % in degrees, simulated drift % IFCHANGE
eye.drift.pos(:, 2)=eye.drift.move(1,2)*sin(linspace(0, eye.drift.move(2,2)*pi,eye.nFrames)+.25); % in degrees
end
end
function stim=MakeScotoma(stim)
disp('Generating scotoma ...');
scot=zeros(size(stim.XDeg));
scot(sqrt((stim.XDeg-stim.scotoma.center(2)).^2+(stim.YDeg-stim.scotoma.center(1)).^2)<stim.scotoma.rad)=0;
scot(sqrt((stim.XDeg-stim.scotoma.center(2)).^2+(stim.YDeg-stim.scotoma.center(1)).^2)>=stim.scotoma.rad)=1;
stim.scotoma.img=scot;
end
function stim=MakeBar(stim)
%% create the bar stimulus
% will create a mask for the bar stimulus. whatever the Hz rate of updating
% the stimulus is ~8Hz, will have the necessary number of bars.
h = waitbar(0,'Generating bar stimulus');
stim.bar.speed = [2,3]; %speed range degrees/sec
stim.bar.width=6;
direction = rand(1)*360;
speed = rand(1)*(stim.bar.speed(2)-stim.bar.speed(2))+stim.bar.speed(1);
center = -(max(stim.XDeg(:))+stim.bar.width/2)*[cos(direction*pi/180),sin(direction*pi/180)];
dx = cos(direction*pi/180)*speed*(1/stim.background.hz);
dy = sin(direction*pi/180)*speed*(1/stim.background.hz);
stim.center = zeros(stim.npos,2);
stim.ang = zeros(stim.npos,1);
stim.img = zeros([size(stim.XDeg),stim.npos],'uint8');
for flipNum = 1:stim.npos
center = center + [dx,dy];
if norm(center)>max(stim.XDeg(:))+stim.bar.width/2;
direction = rand(1)*360;
center = -(max(stim.XDeg(:))+stim.bar.width/2)*[cos(direction*pi/180),sin(direction*pi/180)];
dx = cos(direction*pi/180)*speed*(1/stim.background.hz);
dy = sin(direction*pi/180)*speed*(1/stim.background.hz);
speed = rand(1)*(stim.bar.speed(2)-stim.bar.speed(2))+stim.bar.speed(1);
end
stim.center(flipNum,:) = center;
stim.ang(flipNum) = direction+90;
% mask = false([size(XDeg),stim.npos]);
% a = cos(stim.ang(flipNum)*pi/180)*(XDeg-stim.center(flipNum,1)) + sin(stim.ang(flipNum)*pi/180)*(YDeg-stim.center(flipNum,2));
b = -sin(stim.ang(flipNum)*pi/180)*(stim.XDeg-stim.center(flipNum,1)) +cos(stim.ang(flipNum)*pi/180)*(stim.YDeg-stim.center(flipNum,2));
stim.img(:,:,flipNum) = uint8((abs(b)<stim.bar.width/2));
waitbar(flipNum/stim.npos,h);
end
delete(h);
end
function stim=MakeMF(stim)
h = waitbar(0,'Generating multifocal stimulus');
stim.mf.outer=max(stim.XDeg(:)); %radius outer ring in degrees
stim.stimSeq = generateMultifocalSequence(stim.mf.sectors,stim.mf.nrings,stim.npos, stim.mf.noneighbors);
if stim.logscaled==1
stim.mf.ringpos=exp(linspace(log(stim.mf.inner), log(stim.mf.outer), stim.mf.nrings+1));% radii position of each ring
else
stim.mf.ringpos=linspace(stim.mf.inner, stim.mf.outer, stim.mf.nrings+1);
end
% describe how the stimulus rotates across the scan, this gradual rotation
% allows pRFs to be estimated more accurately visual space is sampled more
% finely
a=linspace(0, (360/stim.mf.sectors), ceil(stim.npos/(stim.mf.nrot*2))+1);
a=[a fliplr(a(2:end-1))]; % add the reversal
stim.mf.rotpos=repmat(a, 1, ceil(stim.npos/length(a)));
stim.mf.rotpos=stim.mf.rotpos(1:stim.npos);
% describe how the stimulus expands/contracts across the scan, ditto
maxscFac=(max(stim.XDeg(:))-diff(stim.mf.ringpos(1:2)))./max(stim.XDeg(:));
a=linspace(1, maxscFac, ceil(stim.npos/(stim.mf.nEC*2))+1);
a=[a fliplr(a(2:end-1))]; % add the reversal
stim.mf.ECscale=repmat(a, 1, ceil(stim.npos/length(a)));
stim.mf.ECscale=stim.mf.ECscale(1:stim.npos);
rad=zeros(size(stim.XDeg));
for i=1:length(stim.mf.ringpos)-1 % fill in the rings
rad(stim.RDeg>stim.mf.ringpos(i) & stim.RDeg<=stim.mf.ringpos(i+1))=i.*stim.mf.sectors;
end
% calculate the sectors
theta=ceil(scaleif(stim.T,0,stim.mf.sectors)).*(rad>0);% window by the rings
finalimg=((theta+rad)-stim.mf.sectors).*(rad>0);
for flipNum = 1:stim.npos % for each version of the MF sequence
img=zeros(size(finalimg));
onlist=find(stim.stimSeq(:, flipNum));
for o=1:length(onlist)
img(finalimg==onlist(o))=1;
end
% add black lines to avoid aliasing
% img(mod(T, 1)<0.05)=0;
% rotate the image
img = imrotate(img,stim.mf.rotpos(flipNum),'nearest', 'crop');
% scale the image
img = imresize(img, stim.mf.ECscale(flipNum), 'nearest');
stim.img(:,:,flipNum) = insertImg(zeros(size(stim.X)), img);
waitbar(flipNum/stim.npos,h);
end
delete(h);
end
|
github
|
ionefine/retinotopic-mapping-master
|
doSimonScotoma.m
|
.m
|
retinotopic-mapping-master/doSimonScotoma.m
| 7,558 |
utf_8
|
8be74c9758f5c77974078edc16f1b274
|
function s=doSimonScotoma(display,s,curTime)
%s=doSimon(display,s,curTime)
escPressed=0;
switch s.action
case 'init' %set up simon variables
% 'simon' parameters
if ~isfield(s, 'scFac')
s.scFac=1;
end
s.size = [6,20,24,3]*s.scFac; %pixels
s.gap = 2; %pixels
s.c = ceil(display.resolution/2)+s.fixoffset;
for i=1:length(s.size)
s.rect{i} = [-s.size(i)/2+s.c(1),-s.size(i)/2+s.c(2),+s.size(i)/2+s.c(1),+s.size(i)/2+s.c(2)];
end
s.ISI = 1; %seconds
s.dur = .75; %seconds
s.pauseDur = .5; %seconds
s.errDur = 1; %seconds
s.errFreq = 4; %Hz
s.color{1} = [0,0,255];
s.color{2} = [255,255,0];
s.color{3} = [0,255,0];
s.color{4} = [255,0,0];
s.goodKeys = [1,2,3,4];
s.keys = {'b','y','g','r'};
%s.keys = {'w','s','a','q'}; %for 1,2,3,4
s.seq = [];
s.maxLen = [];
s.i = 0;
s.state = 'off';
s.seq = s.goodKeys(ceil(rand(1)*length(s.goodKeys)));
s.pauseTill = 1;
s.action = 'play';
s.event.type = 'switch to play';
s.event.time = 0;
s.event.num = 0;
s.numEvents = 1;
showSimon(display,s);
case 'play' %sequence playback mode
if s.pauseTill < curTime
t = mod(curTime,s.ISI);
if strcmp(s.state,'off') && t<=s.dur
s.i = s.i+1;
if s.i<=length(s.seq);
s.show = s.seq(s.i);
s.state = 'on';
s.numEvents = s.numEvents+1;
s.event(s.numEvents).type= 'play: on';
s.event(s.numEvents).time = curTime;
s.event(s.numEvents).num = s.show;
else
s.numEvents = s.numEvents+1;
s.event(s.numEvents).type= 'switch to recall';
s.event(s.numEvents).time = curTime;
s.event(s.numEvents).num = NaN;
s.action = 'recall';
s.state = 'off';
s.i = 0;
end
elseif strcmp(s.state,'on') && t> s.dur
s.numEvents = s.numEvents+1;
s.event(s.numEvents).type= 'play: off';
s.event(s.numEvents).time = curTime;
s.event(s.numEvents).num = s.show;
s.state = 'off';
end
end
showSimon(display,s);
case 'recall'
if s.pauseTill<curTime
%see if a key is pressed
[ keyIsDown, timeSecs, keyCode ] = KbCheck;
if keyIsDown && strcmp(s.state,'off') %a key is down: record the key and time pressed
keyPressed= KbName(keyCode);
keyNum = find(strcmp(keyPressed(end),s.keys));
if ~isempty(keyNum)
s.show = keyNum;
s.state = 'on';
s.numEvents = s.numEvents+1;
s.event(s.numEvents).type= 'recall: on';
s.event(s.numEvents).time = curTime;
s.event(s.numEvents).num = s.show;
end
elseif ~keyIsDown && strcmp(s.state,'on') %key just lifted
s.state = 'off';
s.numEvents = s.numEvents+1;
s.event(s.numEvents).type= 'recall: off';
s.event(s.numEvents).time = curTime;
s.event(s.numEvents).num = NaN;
s.i = s.i+1;
if s.show ~= s.seq(s.i)
%incorrect
s.maxLen = [s.maxLen,length(s.seq)-1];
s.pauseTill = ceil(curTime+ s.errDur);
s.action = 'error';
s.numEvents = s.numEvents+1;
s.event(s.numEvents).type= 'error: start';
s.event(s.numEvents).time = curTime;
s.event(s.numEvents).num = s.seq(end);
elseif s.i == length(s.seq) %got the last one right
s.seq = [s.seq,s.goodKeys(ceil(rand(1)*length(s.goodKeys)))];
s.state = 'off';
s.action = 'play';
s.i = 0;
s.pauseTill = ceil(curTime+ s.pauseDur) ;
s.numEvents = s.numEvents+1;
s.event(s.numEvents).type= 'switch to play';
s.event(s.numEvents).time = curTime;
s.event(s.numEvents).num = NaN;
end
end
end
showSimon(display,s);
case 'error'
if curTime < s.pauseTill
ab = mod(curTime*s.errFreq,1);
s.show = s.seq(end);
if ab<.5
s.state = 'on';
else
s.state = 'off';
end
showSimon(display,s);
else
s.i = 0;
s.seq = s.goodKeys(ceil(rand(1)*length(s.goodKeys)));
s.action = 'play';
s.state = 'off';
s.pauseTill = ceil(curTime+ s.pauseDur);
s.numEvents = s.numEvents+1;
s.event(s.numEvents).type= 'error: stop';
s.event(s.numEvents).time = curTime;
s.event(s.numEvents).num = NaN;
end
case 'done'
s.maxLen = [s.maxLen,length(s.seq)-1];
s.numEvents = s.numEvents+1;
s.event(s.numEvents).type= 'done';
s.event(s.numEvents).time = curTime;
s.event(s.numEvents).num = NaN;
s.seq = [];
end
end
function showSimon(display,s)
s.c = ceil(display.resolution/2)+s.fixoffset;
for i=1:length(s.size)
s.rect{i} = [-s.size(i)/2+s.c(1),-s.size(i)/2+s.c(2),+s.size(i)/2+s.c(1),+s.size(i)/2+s.c(2)];
end
switch s.state
case 'on';
Screen('FillOval',display.windowPtr,[100,100,100],s.rect{3});
Screen('FillArc',display.windowPtr,s.color{s.show},s.rect{2},90*(s.show-1),90);
Screen('FillRect',display.windowPtr,[128,128,128],[s.c(1)-s.size(2)/2,s.c(2)-s.gap/2,s.c(1)+s.size(2)/2,s.c(2)+s.gap/2]);
Screen('FillRect',display.windowPtr,[128,128,128],[s.c(1)-s.gap/2,s.c(2)-s.size(2)/2,s.c(1)+s.gap/2,s.c(2)+s.size(2)/2]);
Screen('FillOval',display.windowPtr,[128,128,128],s.rect{1});
Screen('FillOval',display.windowPtr,[255,255,255],s.rect{4});
case 'off'
Screen('FillOval',display.windowPtr,[100,100,100],s.rect{3});
Screen('FillRect',display.windowPtr,[128,128,128],[s.c(1)-s.size(2)/2,s.c(2)-s.gap/2,s.c(1)+s.size(2)/2,s.c(2)+s.gap/2]);
Screen('FillRect',display.windowPtr,[128,128,128],[s.c(1)-s.gap/2,s.c(2)-s.size(2)/2,s.c(1)+s.gap/2,s.c(2)+s.size(2)/2]);
Screen('FillOval',display.windowPtr,[128,128,128],s.rect{1});
Screen('FillOval',display.windowPtr,[255,255,255],s.rect{4});
otherwise
disp(sprintf('state %s not recognized',s.state));
end
end
|
github
|
3arbouch/PersonDetection-master
|
imagesAlign.m
|
.m
|
PersonDetection-master/Source/toolbox/videos/imagesAlign.m
| 8,167 |
utf_8
|
d125eb5beb502d940be5bd145521f34b
|
function [H,Ip] = imagesAlign( I, Iref, varargin )
% Fast and robust estimation of homography relating two images.
%
% The algorithm for image alignment is a simple but effective variant of
% the inverse compositional algorithm. For a thorough overview, see:
% "Lucas-kanade 20 years on A unifying framework,"
% S. Baker and I. Matthews. IJCV 2004.
% The implementation is optimized and can easily run at 20-30 fps.
%
% type may take on the following values:
% 'translation' - translation only
% 'rigid' - translation and rotation
% 'similarity' - translation, rotation and scale
% 'affine' - 6 parameter affine transform
% 'rotation' - pure rotation (about x, y and z)
% 'projective' - full 8 parameter homography
% Alternatively, type may be a vector of ids between 1 and 8, specifying
% exactly the types of transforms allowed. The ids correspond, to: 1:
% translate-x, 2: translate-y, 3: uniform scale, 4: shear, 5: non-uniform
% scale, 6: rotate-z, 7: rotate-x, 8: rotate-y. For example, to specify
% translation use type=[1,2]. If the transforms don't form a group, the
% returned homography may have more degrees of freedom than expected.
%
% Parameters (in rough order of importance): [resample] controls image
% downsampling prior to computing H. Runtime is proportional to area, so
% using resample<1 can dramatically speed up alignment, and in general not
% degrade performance much. [sig] controls image smoothing, sig=2 gives
% good performance, setting sig too low causes loss of information and too
% high will violate the linearity assumption. [epsilon] defines the
% stopping criteria, use to adjust performance versus speed tradeoff.
% [lambda] is a regularization term that causes small transforms to be
% favored, in general any small non-zero setting of lambda works well.
% [outThr] is a threshold beyond which pixels are considered outliers, be
% careful not to set too low. [minArea] determines coarsest scale beyond
% which the image is not downsampled (should not be set too low). [H0] can
% be used to specify an initial alignment. Use [show] to display results.
%
% USAGE
% [H,Ip] = imagesAlign( I, Iref, varargin )
%
% INPUTS
% I - transformed version of I
% Iref - reference grayscale double image
% varargin - additional params (struct or name/value pairs)
% .type - ['projective'] see above for options
% .resample - [1] image resampling prior to homography estimation
% .sig - [2] amount of Gaussian spatial smoothing to apply
% .epsilon - [1e-3] stopping criteria (min change in error)
% .lambda - [1e-6] regularization term favoring small transforms
% .outThr - [inf] outlier threshold
% .minArea - [4096] minimum image area in coarse to fine search
% .H0 - [eye(3)] optional initial homography estimate
% .show - [0] optionally display results in figure show
%
% OUTPUTS
% H - estimated homography to transform I into Iref
% Ip - tranformed version of I (slow to compute)
%
% EXAMPLE
% Iref = double(imread('cameraman.tif'))/255;
% H0 = [eye(2)+randn(2)*.1 randn(2,1)*10; randn(1,2)*1e-3 1];
% I = imtransform2(Iref,H0^-1,'pad','replicate');
% o=50; P=ones(o)*1; I(150:149+o,150:149+o)=P;
% prmAlign={'outThr',.1,'resample',.5,'type',1:8,'show'};
% [H,Ip]=imagesAlign(I,Iref,prmAlign{:},1);
% tic, for i=1:30, H=imagesAlign(I,Iref,prmAlign{:},0); end;
% t=toc; fprintf('average fps: %f\n',30/t)
%
% See also imTransform2
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get parameters
dfs={'type','projective','resample',1,'sig',2,'epsilon',1e-3,...
'lambda',1e-6,'outThr',inf,'minArea',4096,'H0',eye(3),'show',0};
[type,resample,sig,epsilon,lambda,outThr,minArea,H0,show] = ...
getPrmDflt(varargin,dfs,1);
filt = filterGauss(2*ceil(sig*2.5)+1,[],sig^2);
% determine type of transformation to recover
if(isnumeric(type)), assert(length(type)<=8); else
id=find(strcmpi(type,{'translation','rigid','similarity','affine',...
'rotation','projective'})); msgId='piotr:imagesAlign';
if(isempty(id)), error(msgId,'unknown type: %s',type); end
type={1:2,[1:2 6],[1:3 6],1:6,6:8,1:8}; type=type{id};
end; keep=zeros(1,8); keep(type)=1; keep=keep>0;
% compute image alignment (optionally resample first)
prm={keep,filt,epsilon,H0,minArea,outThr,lambda};
if( resample==1 ), H=imagesAlign1(I,Iref,prm); else
S=eye(3); S([1 5])=resample; H0=S*H0*S^-1; prm{4}=H0;
I1=imResample(I,resample); Iref1=imResample(Iref,resample);
H=imagesAlign1(I1,Iref1,prm); H=S^-1*H*S;
end
% optionally rectify I and display results (can be expensive)
if(nargout==1 && show==0), return; end
Ip = imtransform2(I,H,'pad','replicate');
if(show), figure(show); clf; s=@(i) subplot(2,3,i);
Is=[I Iref Ip]; ri=[min(Is(:)) max(Is(:))];
D0=abs(I-Iref); D1=abs(Ip-Iref); Ds=[D0 D1]; di=[min(Ds(:)) max(Ds(:))];
s(1); im(I,ri,0); s(2); im(Iref,ri,0); s(3); im(D0,di,0);
s(4); im(Ip,ri,0); s(5); im(Iref,ri,0); s(6); im(D1,di,0);
s(3); title('|I-Iref|'); s(6); title('|Ip-Iref|');
end
end
function H = imagesAlign1( I, Iref, prm )
% apply recursively if image large
[keep,filt,epsilon,H0,minArea,outThr,lambda]=deal(prm{:});
[h,w]=size(I); hc=mod(h,2); wc=mod(w,2);
if( w*h<minArea ), H=H0; else
I1=imResample(I(1:(h-hc),1:(w-wc)),.5);
Iref1=imResample(Iref(1:(h-hc),1:(w-wc)),.5);
S=eye(3); S([1 5])=2; H0=S^-1*H0*S; prm{4}=H0;
H=imagesAlign1(I1,Iref1,prm); H=S*H*S^-1;
end
% smooth images (pad first so dimensions unchanged)
O=ones(1,(length(filt)-1)/2); hs=[O 1:h h*O]; ws=[O 1:w w*O];
Iref=conv2(conv2(Iref(hs,ws),filt','valid'),filt,'valid');
I=conv2(conv2(I(hs,ws),filt','valid'),filt,'valid');
% pad images with nan so later can determine valid regions
hs=[1 1 1:h h h]; ws=[1 1 1:w w w]; I=I(hs,ws); Iref=Iref(hs,ws);
hs=[1:2 h+3:h+4]; I(hs,:)=nan; Iref(hs,:)=nan;
ws=[1:2 w+3:w+4]; I(:,ws)=nan; Iref(:,ws)=nan;
% convert weights hardcoded for 128x128 image to given image dims
wts=[1 1 1.0204 .03125 1.0313 0.0204 .00055516 .00055516];
s=sqrt(numel(Iref))/128;
wts=[wts(1:2) wts(3)^(1/s) wts(4)/s wts(5)^(1/s) wts(6)/s wts(7:8)/(s*s)];
% prepare subspace around Iref
[~,Hs]=ds2H(-ones(1,8),wts); Hs=Hs(:,:,keep); K=size(Hs,3);
[h,w]=size(Iref); Ts=zeros(h,w,K); k=0;
if(keep(1)), k=k+1; Ts(:,1:end-1,k)=Iref(:,2:end); end
if(keep(2)), k=k+1; Ts(1:end-1,:,k)=Iref(2:end,:); end
pTransf={'method','bilinear','pad','none','useCache'};
for i=k+1:K, Ts(:,:,i)=imtransform2(Iref,Hs(:,:,i),pTransf{:},1); end
Ds=Ts-Iref(:,:,ones(1,K)); Mref = ~any(isnan(Ds),3);
if(0), figure(10); montage2(Ds); end
Ds = reshape(Ds,[],size(Ds,3));
% iteratively project Ip onto subspace, storing transformation
lambda=lambda*w*h*eye(K); ds=zeros(1,8); err=inf;
for i=1:100
s=svd(H); if(s(3)<=1e-4*s(1)), H=eye(3); return; end
Ip=imtransform2(I,H,pTransf{:},0); dI=Ip-Iref; dI0=abs(dI);
M=Mref & ~isnan(Ip); M0=M; if(outThr<inf), M=M & dI0<outThr; end
M1=find(M); D=Ds(M1,:); ds1=(D'*D + lambda)^(-1)*(D'*dI(M1));
if(any(isnan(ds1))), ds1=zeros(K,1); end
ds(keep)=ds1; H1=ds2H(ds,wts); H=H*H1; H=H/H(9);
err0=err; err=dI0; err(~M0)=0; err=mean2(err); del=err0-err;
if(0), fprintf('i=%03i err=%e del=%e\n',i,err,del); end
if( del<epsilon ), break; end
end
end
function [H,Hs] = ds2H( ds, wts )
% compute homography from offsets ds
Hs=eye(3); Hs=Hs(:,:,ones(1,8));
Hs(2,3,1)=wts(1)*ds(1); % 1 x translation
Hs(1,3,2)=wts(2)*ds(2); % 2 y translation
Hs(1:2,1:2,3)=eye(2)*wts(3)^ds(3); % 3 scale
Hs(2,1,4)=wts(4)*ds(4); % 4 shear
Hs(1,1,5)=wts(5)^ds(5); % 5 scale non-uniform
ct=cos(wts(6)*ds(6)); st=sin(wts(6)*ds(6));
Hs(1:2,1:2,6)=[ct -st; st ct]; % 6 rotation about z
ct=cos(wts(7)*ds(7)); st=sin(wts(7)*ds(7));
Hs([1 3],[1 3],7)=[ct -st; st ct]; % 7 rotation about x
ct=cos(wts(8)*ds(8)); st=sin(wts(8)*ds(8));
Hs(2:3,2:3,8)=[ct -st; st ct]; % 8 rotation about y
H=eye(3); for i=1:8, H=Hs(:,:,i)*H; end
end
|
github
|
3arbouch/PersonDetection-master
|
opticalFlow.m
|
.m
|
PersonDetection-master/Source/toolbox/videos/opticalFlow.m
| 7,361 |
utf_8
|
b97e8c1f623eca07c6f1a0fff26d171e
|
function [Vx,Vy,reliab] = opticalFlow( I1, I2, varargin )
% Coarse-to-fine optical flow using Lucas&Kanade or Horn&Schunck.
%
% Implemented 'type' of optical flow estimation:
% LK: http://en.wikipedia.org/wiki/Lucas-Kanade_method
% HS: http://en.wikipedia.org/wiki/Horn-Schunck_method
% SD: Simple block-based sum of absolute differences flow
% LK is a local, fast method (the implementation is fully vectorized).
% HS is a global, slower method (an SSE implementation is provided).
% SD is a simple but potentially expensive approach.
%
% Common parameters: 'smooth' determines smoothing prior to computing flow
% and can make flow estimation more robust. 'filt' determines amount of
% median filtering of the computed flow field which improves results but is
% costly. 'minScale' and 'maxScale' control image scales in the pyramid.
% Setting 'maxScale'<1 results in faster but lower quality results, e.g.
% maxScale=.5 makes flow computation about 4x faster. Method specific
% parameters: 'radius' controls window size (and smoothness of flow) for LK
% and SD. 'nBlock' determines number of blocks tested in each direction for
% SD, computation time is O(nBlock^2). For HS, 'alpha' controls tradeoff
% between data and smoothness term (and smoothness of flow) and 'nIter'
% determines number of gradient decent steps.
%
% USAGE
% [Vx,Vy,reliab] = opticalFlow( I1, I2, pFlow )
%
% INPUTS
% I1, I2 - input images to calculate flow between
% pFlow - parameters (struct or name/value pairs)
% .type - ['LK'] may be 'LK', 'HS' or 'SD'
% .smooth - [1] smoothing radius for triangle filter (may be 0)
% .filt - [0] median filtering radius for smoothing flow field
% .minScale - [1/64] minimum pyramid scale (must be a power of 2)
% .maxScale - [1] maximum pyramid scale (must be a power of 2)
% .radius - [10] integration radius for weighted window [LK/SD only]
% .nBlock - [5] number of tested blocks [SD only]
% .alpha - [1] smoothness constraint [HS only]
% .nIter - [250] number of iterations [HS only]
%
% OUTPUTS
% Vx, Vy - x,y components of flow [Vx>0->right, Vy>0->down]
% reliab - reliability of flow in given window
%
% EXAMPLE - compute LK flow on test images
% load opticalFlowTest;
% [Vx,Vy]=opticalFlow(I1,I2,'smooth',1,'radius',10,'type','LK');
% figure(1); im(I1); figure(2); im(I2);
% figure(3); im([Vx Vy]); colormap jet;
%
% EXAMPLE - rectify I1 to I2 using computed flow
% load opticalFlowTest;
% [Vx,Vy]=opticalFlow(I1,I2,'smooth',1,'radius',10,'type','LK');
% I1=imtransform2(I1,[],'vs',-Vx,'us',-Vy,'pad','replicate');
% figure(1); im(I1); figure(2); im(I2);
%
% EXAMPLE - compare LK/HS/SD flows
% load opticalFlowTest;
% prm={'smooth',1,'radius',10,'alpha',20,'nIter',250,'type'};
% tic, [Vx1,Vy1]=opticalFlow(I1,I2,prm{:},'LK'); toc
% tic, [Vx2,Vy2]=opticalFlow(I1,I2,prm{:},'HS'); toc
% tic, [Vx3,Vy3]=opticalFlow(I1,I2,prm{:},'SD','minScale',1); toc
% figure(1); im([Vx1 Vy1; Vx2 Vy2; Vx3 Vy3]); colormap jet;
%
% See also convTri, imtransform2, medfilt2
%
% Piotr's Computer Vision Matlab Toolbox Version 3.24
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get default parameters and do error checking
dfs={ 'type','LK', 'smooth',1, 'filt',0, 'minScale',1/64, ...
'maxScale',1, 'radius',10, 'nBlock',5, 'alpha',1, 'nIter',250 };
[type,smooth,filt,minScale,maxScale,radius,nBlock,alpha,nIter] = ...
getPrmDflt(varargin,dfs,1);
assert(any(strcmp(type,{'LK','HS','SD'})));
if( ~ismatrix(I1) || ~ismatrix(I2) || any(size(I1)~=size(I2)) )
error('Input images must be 2D and have same dimensions.'); end
% run optical flow in coarse to fine fashion
if(~isa(I1,'single')), I1=single(I1); I2=single(I2); end
[h,w]=size(I1); nScales=max(1,floor(log2(min([h w 1/minScale])))+1);
for s=1:max(1,nScales + round(log2(maxScale)))
% get current scale and I1s and I2s at given scale
scale=2^(nScales-s); h1=round(h/scale); w1=round(w/scale);
if( scale==1 ), I1s=I1; I2s=I2; else
I1s=imResample(I1,[h1 w1]); I2s=imResample(I2,[h1 w1]); end
% initialize Vx,Vy or upsample from previous scale
if(s==1), Vx=zeros(h1,w1,'single'); Vy=Vx; else r=sqrt(h1*w1/numel(Vx));
Vx=imResample(Vx,[h1 w1])*r; Vy=imResample(Vy,[h1 w1])*r; end
% transform I2s according to current estimate of Vx and Vy
if(s>1), I2s=imtransform2(I2s,[],'pad','replciate','vs',Vx,'us',Vy); end
% smooth images
I1s=convTri(I1s,smooth); I2s=convTri(I2s,smooth);
% run optical flow on current scale
switch type
case 'LK', [Vx1,Vy1,reliab]=opticalFlowLk(I1s,I2s,radius);
case 'HS', [Vx1,Vy1,reliab]=opticalFlowHs(I1s,I2s,alpha,nIter);
case 'SD', [Vx1,Vy1,reliab]=opticalFlowSd(I1s,I2s,radius,nBlock,1);
end
Vx=Vx+Vx1; Vy=Vy+Vy1;
% finally median filter the resulting flow field
if(filt), Vx=medfilt2(Vx,[filt filt],'symmetric'); end
if(filt), Vy=medfilt2(Vy,[filt filt],'symmetric'); end
end
r=sqrt(h*w/numel(Vx));
if(r~=1), Vx=imResample(Vx,[h w])*r; Vy=imResample(Vy,[h w])*r; end
if(r~=1 && nargout==3), reliab=imResample(reliab,[h w]); end
end
function [Vx,Vy,reliab] = opticalFlowLk( I1, I2, radius )
% Compute elements of A'A and also of A'b
radius=min(radius,floor(min(size(I1,1),size(I1,2))/2)-1);
[Ix,Iy]=gradient2(I1); It=I2-I1; AAxy=convTri(Ix.*Iy,radius);
AAxx=convTri(Ix.^2,radius)+1e-5; ABxt=convTri(-Ix.*It,radius);
AAyy=convTri(Iy.^2,radius)+1e-5; AByt=convTri(-Iy.*It,radius);
% Find determinant and trace of A'A
AAdet=AAxx.*AAyy-AAxy.^2; AAdeti=1./AAdet; AAtr=AAxx+AAyy;
% Compute components of velocity vectors (A'A)^-1 * A'b
Vx = AAdeti .* ( AAyy.*ABxt - AAxy.*AByt);
Vy = AAdeti .* (-AAxy.*ABxt + AAxx.*AByt);
% Check for ill conditioned second moment matrices
reliab = 0.5*AAtr - 0.5*sqrt(AAtr.^2-4*AAdet);
end
function [Vx,Vy,reliab] = opticalFlowHs( I1, I2, alpha, nIter )
% compute derivatives (averaging over 2x2 neighborhoods)
pad = @(I,p) imPad(I,p,'replicate');
crop = @(I,c) I(1+c:end-c,1+c:end-c);
Ex = I1(:,2:end)-I1(:,1:end-1) + I2(:,2:end)-I2(:,1:end-1);
Ey = I1(2:end,:)-I1(1:end-1,:) + I2(2:end,:)-I2(1:end-1,:);
Ex = Ex/4; Ey = Ey/4; Et = (I2-I1)/4;
Ex = pad(Ex,[1 1 1 2]) + pad(Ex,[0 2 1 2]);
Ey = pad(Ey,[1 2 1 1]) + pad(Ey,[1 2 0 2]);
Et=pad(Et,[0 2 1 1])+pad(Et,[1 1 1 1])+pad(Et,[1 1 0 2])+pad(Et,[0 2 0 2]);
Z=1./(alpha*alpha + Ex.*Ex + Ey.*Ey); reliab=crop(Z,1);
% iterate updating Ux and Vx in each iter
if( 1 )
[Vx,Vy]=opticalFlowHsMex(Ex,Ey,Et,Z,nIter);
Vx=crop(Vx,1); Vy=crop(Vy,1);
else
Ex=crop(Ex,1); Ey=crop(Ey,1); Et=crop(Et,1); Z=crop(Z,1);
Vx=zeros(size(I1),'single'); Vy=Vx;
f=single([0 1 0; 1 0 1; 0 1 0])/4;
for i = 1:nIter
Mx=conv2(Vx,f,'same'); My=conv2(Vy,f,'same');
m=(Ex.*Mx+Ey.*My+Et).*Z; Vx=Mx-Ex.*m; Vy=My-Ey.*m;
end
end
end
function [Vx,Vy,reliab] = opticalFlowSd( I1, I2, radius, nBlock, step )
% simple block-based sum of absolute differences flow
[h,w]=size(I1); k=2*nBlock+1; k=k*k; D=zeros(h,w,k,'single'); k=1;
rng = @(x,w) max(1+x*step,1):min(w+x*step,w);
for x=-nBlock:nBlock, xs0=rng(x,w); xs1=rng(-x,w);
for y=-nBlock:nBlock, ys0=rng(y,h); ys1=rng(-y,h);
D(ys0,xs0,k)=abs(I1(ys0,xs0)-I2(ys1,xs1)); k=k+1;
end
end
D=convTri(D,radius); [reliab,D]=min(D,[],3);
k=2*nBlock+1; Vy=mod(D-1,k)+1; Vx=(D-Vy)/k+1;
Vy=(nBlock+1-Vy)*step; Vx=(nBlock+1-Vx)*step;
end
|
github
|
3arbouch/PersonDetection-master
|
seqWriterPlugin.m
|
.m
|
PersonDetection-master/Source/toolbox/videos/seqWriterPlugin.m
| 8,280 |
utf_8
|
597792f79fff08b8bb709313267c3860
|
function varargout = seqWriterPlugin( cmd, h, varargin )
% Plugin for seqIo and videoIO to allow writing of seq files.
%
% Do not call directly, use as plugin for seqIo or videoIO instead.
% The following is a list of commands available (swp=seqWriterPlugin):
% h=swp('open',h,fName,info) % Open a seq file for writing (h ignored).
% h=swp('close',h) % Close seq file (output h is -1).
% swp('addframe',h,I,[ts]) % Writes video frame (and timestamp).
% swp('addframeb',h,I,[ts]) % Writes video frame with no encoding.
% info = swp('getinfo',h) % Return struct with info about video.
%
% The following params must be specified in struct 'info' upon opening:
% width - frame width
% height - frame height
% fps - frames per second
% quality - [80] compression quality (0 to 100)
% codec - string representing codec, options include:
% 'monoraw'/'imageFormat100' - black/white uncompressed
% 'raw'/'imageFormat200' - color (BGR) uncompressed
% 'monojpg'/'imageFormat102' - black/white jpg compressed
% 'jpg'/'imageFormat201' - color jpg compressed
% 'monopng'/'imageFormat001' - black/white png compressed
% 'png'/'imageFormat002' - color png compressed
%
% USAGE
% varargout = seqWriterPlugin( cmd, h, varargin )
%
% INPUTS
% cmd - string indicating operation to perform
% h - unique identifier for open seq file
% varargin - additional options (vary according to cmd)
%
% OUTPUTS
% varargout - output (varies according to cmd)
%
% EXAMPLE
%
% See also SEQIO, SEQREADERPLUGIN
%
% Piotr's Computer Vision Matlab Toolbox Version 2.66
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% persistent variables to keep track of all loaded .seq files
persistent h1 hs fids infos tNms;
if(isempty(h1)), h1=int32(now); hs=int32([]); infos={}; tNms={}; end
nIn=nargin-2; in=varargin; o1=[]; cmd=lower(cmd);
% open seq file
if(strcmp(cmd,'open'))
chk(nIn,2); h=length(hs)+1; hs(h)=h1; varargout={h1}; h1=h1+1;
[pth,name]=fileparts(in{1}); if(isempty(pth)), pth='.'; end
fName=[pth filesep name];
[infos{h},fids(h),tNms{h}]=open(fName,in{2}); return;
end
% Get the handle for this instance
[v,h]=ismember(h,hs); if(~v), error('Invalid load plugin handle'); end
fid=fids(h); info=infos{h}; tNm=tNms{h};
% close seq file
if(strcmp(cmd,'close'))
writeHeader(fid,info);
chk(nIn,0); varargout={-1}; fclose(fid); kp=[1:h-1 h+1:length(hs)];
hs=hs(kp); fids=fids(kp); infos=infos(kp);
tNms=tNms(kp); if(exist(tNm,'file')), delete(tNm); end; return;
end
% perform appropriate operation
switch( cmd )
case 'addframe', chk(nIn,1,2); info=addFrame(fid,info,tNm,1,in{:});
case 'addframeb', chk(nIn,1,2); info=addFrame(fid,info,tNm,0,in{:});
case 'getinfo', chk(nIn,0); o1=info;
otherwise, error(['Unrecognized command: "' cmd '"']);
end
infos{h}=info; varargout={o1};
end
function chk(nIn,nMin,nMax)
if(nargin<3), nMax=nMin; end
if(nIn>0 && nMin==0 && nMax==0), error(['"' cmd '" takes no args.']); end
if(nIn<nMin||nIn>nMax), error(['Incorrect num args for "' cmd '".']); end
end
function success = getImgFile( fName )
% create local copy of fName which is in a imagesci/private
fName = [fName '.' mexext]; s = filesep; success = 1;
sName = [fileparts(which('imread.m')) s 'private' s fName];
tName = [fileparts(mfilename('fullpath')) s 'private' s fName];
if(~exist(tName,'file')), success=copyfile(sName,tName); end
end
function [info, fid, tNm] = open( fName, info )
% open video for writing, create space for header
t=[fName '.seq']; if(exist(t,'file')), delete(t); end
t=[fName '-seek.mat']; if(exist(t,'file')), delete(t); end
fid=fopen([fName '.seq'],'w','l'); assert(fid~=-1);
fwrite(fid,zeros(1,1024),'uint8');
% initialize info struct (w all fields necessary for writeHeader)
assert(isfield2(info,{'width','height','fps','codec'},1));
switch(info.codec)
case {'monoraw', 'imageFormat100'}, frmt=100; nCh=1; ext='raw';
case {'raw', 'imageFormat200'}, frmt=200; nCh=3; ext='raw';
case {'monojpg', 'imageFormat102'}, frmt=102; nCh=1; ext='jpg';
case {'jpg', 'imageFormat201'}, frmt=201; nCh=3; ext='jpg';
case {'monopng', 'imageFormat001'}, frmt=001; nCh=1; ext='png';
case {'png', 'imageFormat002'}, frmt=002; nCh=3; ext='png';
otherwise, error('unknown format');
end; s=1;
if(strcmp(ext,'jpg')), s=getImgFile('wjpg8c'); end
if(strcmp(ext,'png')), s=getImgFile('png');
if(s), info.writeImg=@(p) png('write',p{:}); end; end
if(strcmp(ext,'png') && ~s), s=getImgFile('pngwritec');
if(s), info.writeImg=@(p) pngwritec(p{:}); end; end
if(~s), error('Cannot find Matlab''s source image writer'); end
info.imageFormat=frmt; info.ext=ext;
if(any(strcmp(ext,{'jpg','png'}))), info.seek=1024; info.seekNm=t; end
if(~isfield2(info,'quality')), info.quality=80; end
info.imageBitDepth=8*nCh; info.imageBitDepthReal=8;
nByte=info.width*info.height*nCh; info.imageSizeBytes=nByte;
info.numFrames=0; info.trueImageSize=nByte+6+512-mod(nByte+6,512);
% generate unique temporary name
[~,tNm]=fileparts(fName); t=clock; t=mod(t(end),1);
tNm=sprintf('tmp_%s_%15i.%s',tNm,round((t+rand)/2*1e15),ext);
end
function info = addFrame( fid, info, tNm, encode, I, ts )
% write frame
nCh=info.imageBitDepth/8; ext=info.ext; c=info.numFrames+1;
if( encode )
siz = [info.height info.width nCh];
assert(size(I,1)==siz(1) && size(I,2)==siz(2) && size(I,3)==siz(3));
end
switch ext
case 'raw'
% write an uncompressed image (assume imageBitDepthReal==8)
if( ~encode ), assert(numel(I)==info.imageSizeBytes); else
if(nCh==3), t=I(:,:,3); I(:,:,3)=I(:,:,1); I(:,:,1)=t; end
if(nCh==1), I=I'; else I=permute(I,[3,2,1]); end
end
fwrite(fid,I(:),'uint8'); pad=info.trueImageSize-info.imageSizeBytes-6;
case 'jpg'
if( encode )
% write/read to/from temporary .jpg (not that much overhead)
p=struct('quality',info.quality,'comment',{{}},'mode','lossy');
for t=0:99, try wjpg8c(I,tNm,p); fr=fopen(tNm,'r'); assert(fr>0);
break; catch, pause(.01); fr=-1; end; end %#ok<CTCH>
if(fr<0), error(['write fail: ' tNm]); end; I=fread(fr); fclose(fr);
end
assert(I(1)==255 && I(2)==216 && I(end-1)==255 && I(end)==217); % JPG
fwrite(fid,numel(I)+4,'uint32'); fwrite(fid,I); pad=10;
case 'png'
if( encode )
% write/read to/from temporary .png (not that much overhead)
p=cell(1,17); if(nCh==1), p{4}=0; else p{4}=2; end
p{1}=I; p{3}=tNm; p{5}=8; p{8}='none'; p{16}=cell(0,2);
for t=0:99, try info.writeImg(p); fr=fopen(tNm,'r'); assert(fr>0);
break; catch, pause(.01); fr=-1; end; end %#ok<CTCH>
if(fr<0), error(['write fail: ' tNm]); end; I=fread(fr); fclose(fr);
end
fwrite(fid,numel(I)+4,'uint32'); fwrite(fid,I); pad=10;
otherwise, assert(false);
end
% store seek info
if(any(strcmp(ext,{'jpg','png'})))
if(length(info.seek)<c+1), info.seek=[info.seek; zeros(c,1)]; end
info.seek(c+1)=info.seek(c)+numel(I)+10+pad;
end
% write timestamp
if(nargin<6),ts=(c-1)/info.fps; end; s=floor(ts); ms=round(mod(ts,1)*1000);
fwrite(fid,s,'int32'); fwrite(fid,ms,'uint16'); info.numFrames=c;
% pad with zeros
if(pad>0), fwrite(fid,zeros(1,pad),'uint8'); end
end
function writeHeader( fid, info )
fseek(fid,0,'bof');
% first 4 bytes store OxFEED, next 24 store 'Norpix seq '
fwrite(fid,hex2dec('FEED'),'uint32');
fwrite(fid,['Norpix seq' 0 0],'uint16');
% next 8 bytes for version (3) and header size (1024), then 512 for descr
fwrite(fid,[3 1024],'int32');
if(isfield(info,'descr')), d=info.descr(:); else d=('No Description')'; end
d=[d(1:min(256,end)); zeros(256-length(d),1)]; fwrite(fid,d,'uint16');
% write remaining info
vals=[info.width info.height info.imageBitDepth info.imageBitDepthReal ...
info.imageSizeBytes info.imageFormat info.numFrames 0 ...
info.trueImageSize];
fwrite(fid,vals,'uint32');
% store frame rate and pad with 0's
fwrite(fid,info.fps,'float64'); fwrite(fid,zeros(1,432),'uint8');
% write seek info for compressed images to disk
if(any(strcmp(info.ext,{'jpg','png'})))
seek=info.seek(1:info.numFrames); %#ok<NASGU>
try save(info.seekNm,'seek'); catch; end %#ok<CTCH>
end
end
|
github
|
3arbouch/PersonDetection-master
|
kernelTracker.m
|
.m
|
PersonDetection-master/Source/toolbox/videos/kernelTracker.m
| 9,315 |
utf_8
|
4a7d0235f1e518ab5f1c9f1b5450b3f0
|
function [allRct, allSim, allIc] = kernelTracker( I, prm )
% Kernel Tracker from Comaniciu, Ramesh and Meer PAMI 2003.
%
% Implements the algorithm described in "Kernel-Based Object Tracking" by
% Dorin Comaniciu, Visvanathan Ramesh and Peter Meer, PAMI 25, 564-577,
% 2003. This is a fast tracking algorithm that utilizes a histogram
% representation of an object (in this implementation we use color
% histograms, as in the original work). The idea is given a histogram q in
% frame t, find histogram p in frame t+1 that is most similar to q. It
% turns out that this can be formulated as a mean shift problem. Here, the
% kernel is fixed to the Epanechnikov kernel.
%
% This implementation uses mex files to optimize speed, it is significantly
% faster than real time for a single object on a 2GHz standard laptop (as
% of 2007).
%
% If I==[], toy data is created. If rctS==0, the user is queried to
% specify the first rectangle. rctE, denoting the object location in the
% last frame, can optionally be specified. If rctE is given, the model
% histogram at fraction r of the video is (1-r)*histS+r*histE where histS
% and histE are the model histograms from the first and last frame. If
% rctE==0 rectangle in final frame is queried, if rectE==-1 it is not used.
%
% Let T denote the length of the video. Returned values are of length t,
% where t==T if the object was tracked through the whole sequence (ie sim
% does not fall below simThr), otherwise t<=T is equal to the last frame in
% which obj was found. You can test if the object was tracked using:
% success = (size(allRct,1)==size(I,4));
%
% USAGE
% [allRct, allIc, allSim] = kernelTracker( [I], [prm] )
%
% INPUTS
% I - MxNx3xT input video
% [prm]
% .rctS - [0] rectangle denoting initial object location
% .rctE - [-1] rectangle denoting final object location
% .dispFlag - [1] show interactive display
% .scaleSrch - [1] if true search over scale
% .nBit - [4] n=2^nBit, color histograms are [n x n x n]
% .simThr - [.7] sim thr for when obj is considered lost
% .scaleDel - [.9] multiplicative diff between consecutive scales
%
% OUTPUTS
% allRct - [t x 4] array of t locations [x,y,wd,ht]
% allSim - [1 x t] array of similarity measures during tracking
% allIc - [1 x t] cell array of cropped windows containing obj
%
% EXAMPLE
% disp('Select a rectangular region for tracking');
% [allRct,allSim,allIc] = kernelTracker();
% figure(2); clf; plot(allRct);
% figure(3); clf; montage2(allIc,struct('hasChn',true));
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.22
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%%% get parameters (set defaults)
if( nargin<1 ); I=[]; end;
if( nargin<2 ); prm=struct(); end;
dfs = {'scaleSrch',1, 'nBit',4, 'simThr',.7, ...
'dispFlag',1, 'scaleDel',.9, 'rctS',0, 'rctE',-1 };
prm = getPrmDflt( prm, dfs );
scaleSrch=prm.scaleSrch; nBit=prm.nBit; simThr=prm.simThr;
dispFlag=prm.dispFlag; scaleDel=prm.scaleDel;
rctS=prm.rctS; rctE=prm.rctE;
if(isempty(I)); I=toyData(100,1); end;
%%% get rctS and rectE if necessary
rctProp = {'EdgeColor','g','Curvature',[1 1],'LineWidth',2};
if(rctS==0); figure(1); clf; imshow(I(:,:,:,1)); rctS=getrect; end
if(rctE==0); figure(1); clf; imshow(I(:,:,:,end)); rctE=getrect; end
%%% precompute kernels for all relevant scales
rctS=round(rctS); rctS(3:4)=rctS(3:4)-mod(rctS(3:4),2);
pos1 = rctS(1:2)+rctS(3:4)/2; wd=rctS(3); ht=rctS(4);
[mRows,nCols,~,nFrame] = size(I);
nScaleSm = max(1,floor(log(max(10/wd,10/ht))/log(scaleDel)));
nScaleLr = max(1,floor(-log(min(nCols/wd,mRows/ht)/2)/log(scaleDel)));
nScale = nScaleSm+nScaleLr+1; scale = nScaleSm+1;
kernel = repmat( buildKernel(wd,ht), [1 nScale] );
for s=1:nScale
r = power(scaleDel,s-1-nScaleSm);
kernel(s) = buildKernel( wd/r, ht/r );
end
%%% build model histogram for rctS
[Ic,Qc] = cropWindow( I(:,:,:,1), nBit, pos1, wd, ht );
qS = buildHist( Qc, kernel(scale), nBit );
%%% optionally build model histogram for rctE
if(length(rctE)==4);
rctE=round(rctE); rctE(3:4)=rctE(3:4)-mod(rctE(3:4),2);
posE = rctE(1:2)+rctE(3:4)/2; wdE=rctE(3); htE=rctE(4);
kernelE = buildKernel(wdE,htE);
[Ic,Qc] = cropWindow( I(:,:,:,end), nBit, posE, wdE, htE ); %end
qE = buildHist( Qc, kernelE, nBit );
else
qE = qS;
end
%%% setup display
if( dispFlag )
figure(1); clf; hImg=imshow(I(:,:,:,1));
hR = rectangle('Position', rctS, rctProp{:} );
pause(.1);
end
%%% main loop
pos = pos1;
allRct = zeros(nFrame,4); allRct(1,:)=rctS;
allIc = cell(1,nFrame); allIc{1}=Ic;
allSim = zeros(1,nFrame);
for frm = 1:nFrame
Icur = I(:,:,:,frm);
% current model (linearly interpolate)
r=(frm-1)/nFrame; q = qS*(1-r) + qE*r;
if( scaleSrch )
% search over scale
best={}; bestSim=-1; pos1=pos;
for s=max(1,scale-1):min(nScale,scale+1)
[p,pos,Ic,sim]=kernelTracker1(Icur,q,pos1,kernel(s),nBit);
if( sim>bestSim ); best={p,pos,Ic,s}; bestSim=sim; end;
end
[~,pos,Ic,scale]=deal(best{:});
wd=kernel(scale).wd; ht=kernel(scale).ht;
else
% otherwise just do meanshift once
[~,pos,Ic,bestSim]=kernelTracker1(Icur,q,pos,kernel(scale),nBit);
end
% record results
if( bestSim<simThr ); break; end;
rctC=[pos(1)-wd/2 pos(2)-ht/2 wd, ht ];
allIc{frm}=Ic; allRct(frm,:)=rctC;
allSim(frm)=bestSim;
% display
if( dispFlag )
set(hImg,'CData',Icur); title(['bestSim=' num2str(bestSim)]);
delete(hR); hR=rectangle('Position', rctC, rctProp{:} );
if(0); waitforbuttonpress; else drawnow; end
end
end
%%% finalize & display
if( bestSim<simThr ); frm=frm-1; end;
allIc=allIc(1:frm); allRct=allRct(1:frm,:); allSim=allSim(1:frm);
if( dispFlag )
if( bestSim<simThr ); disp('lost target'); end
disp( ['final sim = ' num2str(bestSim) ] );
end
end
function [p,pos,Ic,sim] = kernelTracker1( I, q, pos, kernel, nBit )
mRows=size(I,1); nCols=size(I,2);
wd=kernel.wd; wd2=wd/2;
ht=kernel.ht; ht2=ht/2;
xs=kernel.xs; ys=kernel.ys;
for iter=1:1000
posPrev = pos;
% check if pos in bounds
rct = [pos(1)-wd/2 pos(2)-ht/2 wd, ht ];
if( rct(1)<1 || rct(2)<1 || (rct(1)+wd)>nCols || (rct(2)+ht)>mRows )
pos=posPrev; p=[]; Ic=[]; sim=eps; return;
end
% crop window / compute histogram
[Ic,Qc] = cropWindow( I, nBit, pos, wd, ht );
p = buildHist( Qc, kernel, nBit );
if( iter==20 ); break; end;
% compute meanshift step
w = ktComputeW_c( Qc, q, p, nBit );
posDel = [sum(xs.*w)*wd2, sum(ys.*w)*ht2] / (sum(w)+eps);
posDel = round(posDel+.1);
if(all(posDel==0)); break; end;
pos = pos + posDel;
end
locs=p>0; sim=sum( sqrt(q(locs).*p(locs)) );
end
function kernel = buildKernel( wd, ht )
wd = round(wd/2)*2; xs = linspace(-1,1,wd);
ht = round(ht/2)*2; ys = linspace(-1,1,ht);
[ys,xs] = ndgrid(ys,xs); xs=xs(:); ys=ys(:);
xMag = ys.*ys + xs.*xs; xMag(xMag>1) = 1;
K = 2/pi * (1-xMag); sumK=sum(K);
kernel = struct( 'K',K, 'sumK',sumK, 'xs',xs, 'ys',ys, 'wd',wd, 'ht',ht );
end
function p = buildHist( Qc, kernel, nBit )
p = ktHistcRgb_c( Qc, kernel.K, nBit ) / kernel.sumK;
if(0); p=gaussSmooth(p,.5,'same',2); p=p*(1/sum(p(:))); end;
end
function [Ic,Qc] = cropWindow( I, nBit, pos, wd, ht )
row = pos(2)-ht/2; col = pos(1)-wd/2;
Ic = I(row:row+ht-1,col:col+wd-1,:);
if(nargout==2); Qc=bitshift(reshape(Ic,[],3),nBit-8); end;
end
function I = toyData( n, sigma )
I1 = imresize(imread('peppers.png'),[256 256],'bilinear');
I=ones(512,512,3,n,'uint8')*100;
pos = round(gaussSmooth(randn(2,n)*80,[0 4]))+128;
for i=1:n
I((1:256)+pos(1,i),(1:256)+pos(2,i),:,i)=I1;
I1 = uint8(double(I1) + randn(size(I1))*sigma);
end;
I=I((1:256)+128,(1:256)+128,:,:);
end
% % debugging code
% if( debug )
% figure(1);
% subplot(2,3,2); image( Ic ); subplot(2,3,1); image(Icur);
% rectangle('Position', posToRct(pos0,wd,ht), rctProp{:} );
% subplot(2,3,3); imagesc( reshape(w,wd,ht), [0 5] ); colormap gray;
% subplot(2,3,4); montage2( q ); subplot(2,3,5); montage2( p1 );
% waitforbuttonpress;
% end
% % search over 9 locations (with fixed scale)
% if( locSrch )
% best={}; bestSim=0.0; pos1=pos;
% for lr=-1:1
% for ud=-1:1
% posSt = pos1 + [wd*lr ht*ud];
% [p,pos,Ic,sim] = kernelTracker1(Icur,q,posSt,kernel(scale),nBit);
% if( sim>bestSim ); best={p,pos,Ic}; bestSim=sim; end;
% end
% end
% [p,pos,Ic]=deal(best{:});
% end
%%% background histogram -- seems kind of useless, removed
% if( 0 )
% bgSiz = 3; bgImp = 2;
% rctBgStr = max([1 1],rctS(1:2)-rctS(3:4)*(bgSiz/2-.5));
% rctBgEnd = min([nCols mRows],rctS(1:2)+rctS(3:4)*(bgSiz/2+.5));
% rctBg = [rctBgStr rctBgEnd-rctBgStr+1];
% posBg = rctBg(1:2)+rctBg(3:4)/2; wdBg=rctBg(3); htBg=rctBg(4);
% [IcBg,QcBg] = cropWindow( I(:,:,:,1), nBit, posBg, wdBg, htBg );
% wtBg = double( reshape(kernel.K,ht,wd)==0 );
% pre=rctS(1:2)-rctBg(1:2); pst=rctBg(3:4)-rctS(3:4)-pre;
% wtBg = padarray( wtBg, fliplr(pre), 1, 'pre' );
% wtBg = padarray( wtBg, fliplr(pst), 1, 'post' );
% pBg = buildHist( QcBg, wtBg, [], nBit );
% pWts = min( 1, max(pBg(:))/bgImp./pBg );
% if(0); montage2(pWts); impixelinfo; return; end
% else
% pWts=[];
% end;
% if(~isempty(pWts)); p = p .* pWts; end; % in buildHistogram
|
github
|
3arbouch/PersonDetection-master
|
seqIo.m
|
.m
|
PersonDetection-master/Source/toolbox/videos/seqIo.m
| 17,019 |
utf_8
|
9c631b324bb527372ec3eed3416c5dcc
|
function out = seqIo( fName, action, varargin )
% Utilities for reading and writing seq files.
%
% A seq file is a series of concatentated image frames with a fixed size
% header. It is essentially the same as merging a directory of images into
% a single file. seq files are convenient for storing videos because: (1)
% no video codec is required, (2) seek is instant and exact, (3) seq files
% can be read on any operating system. The main drawback is that each frame
% is encoded independently, resulting in increased file size. The advantage
% over storing as a directory of images is that a single large file is
% created. Currently, either uncompressed, jpg or png compressed frames
% are supported. The seq file format is modeled after the Norpix seq format
% (in fact this reader can be used to read some Norpix seq files). The
% actual work of reading/writing seq files is done by seqReaderPlugin and
% seqWriterPlugin (there is no need to call those functions directly).
%
% seqIo contains a number of utility functions for working with seq files.
% The format for accessing the various utility functions is:
% out = seqIo( fName, 'action', inputs );
% The list of functions and help for each is given below. Also, help on
% individual subfunctions can be accessed by: "help seqIo>action".
%
% Create interface sr for reading seq files.
% sr = seqIo( fName, 'reader', [cache] )
% Create interface sw for writing seq files.
% sw = seqIo( fName, 'writer', info )
% Get info about seq file.
% info = seqIo( fName, 'getInfo' )
% Crop sub-sequence from seq file.
% seqIo( fName, 'crop', tName, frames )
% Extract images from seq file to target directory or array.
% Is = seqIo( fName, 'toImgs', [tDir], [skip], [f0], [f1], [ext] )
% Create seq file from an array or directory of images or from an AVI file.
% seqIo( fName, 'frImgs', info, varargin )
% Convert seq file by applying imgFun(I) to each frame I.
% seqIo( fName, 'convert', tName, imgFun, varargin )
% Replace header of seq file with provided info.
% seqIo( fName, 'newHeader', info )
% Create interface sr for reading dual seq files.
% sr = seqIo( fNames, 'readerDual', [cache] )
%
% USAGE
% out = seqIo( fName, action, varargin )
%
% INPUTS
% fName - seq file to open
% action - controls action (see above)
% varargin - additional inputs (see above)
%
% OUTPUTS
% out - depends on action (see above)
%
% EXAMPLE
%
% See also seqIo>reader, seqIo>writer, seqIo>getInfo, seqIo>crop,
% seqIo>toImgs, seqIo>frImgs, seqIo>convert, seqIo>newHeader,
% seqIo>readerDual, seqPlayer, seqReaderPlugin, seqWriterPlugin
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
switch lower(action)
case {'reader','r'}, out = reader( fName, varargin{:} );
case {'writer','w'}, out = writer( fName, varargin{:} );
case 'getinfo', out = getInfo( fName );
case 'crop', crop( fName, varargin{:} ); out=1;
case 'toimgs', out = toImgs( fName, varargin{:} );
case 'frimgs', frImgs( fName, varargin{:} ); out=1;
case 'convert', convert( fName, varargin{:} ); out=1;
case 'newheader', newHeader( fName, varargin{:} ); out=1;
case {'readerdual','rdual'}, out=readerDual(fName,varargin{:});
otherwise, error('seqIo unknown action: ''%s''',action);
end
end
function sr = reader( fName, cache )
% Create interface sr for reading seq files.
%
% Create interface sr to seq file with the following commands:
% sr.close(); % Close seq file (sr is useless after).
% [I,ts]=sr.getframe(); % Get current frame (returns [] if invalid).
% [I,ts]=sr.getframeb(); % Get current frame with no decoding.
% ts = sr.getts(); % Return timestamps for all frames.
% info = sr.getinfo(); % Return struct with info about video.
% [I,ts]=sr.getnext(); % Shortcut for next() followed by getframe().
% out = sr.next(); % Go to next frame (out=0 on fail).
% out = sr.seek(frame); % Go to specified frame (out=0 on fail).
% out = sr.step(delta); % Go to current frame+delta (out=0 on fail).
%
% If cache>0, reader() will cache frames in memory, so that calls to
% getframe() can avoid disk IO for cached frames (note that only frames
% returned by getframe() are cached). This is useful if the same frames are
% accessed repeatedly. When the cache is full, the frame in the cache
% accessed least recently is discarded. Memory requirements are
% proportional to cache size.
%
% USAGE
% sr = seqIo( fName, 'reader', [cache] )
%
% INPUTS
% fName - seq file name
% cache - [0] size of cache
%
% OUTPUTS
% sr - interface for reading seq file
%
% EXAMPLE
%
% See also seqIo, seqReaderPlugin
if(nargin<2 || isempty(cache)), cache=0; end
if( cache>0 ), [as, fs, Is, ts, inds]=deal([]); end
r=@seqReaderPlugin; s=r('open',int32(-1),fName);
sr = struct( 'close',@() r('close',s), 'getframe',@getframe, ...
'getframeb',@() r('getframeb',s), 'getts',@() r('getts',s), ...
'getinfo',@() r('getinfo',s), 'getnext',@() r('getnext',s), ...
'next',@() r('next',s), 'seek',@(f) r('seek',s,f), ...
'step',@(d) r('step',s,d));
function [I,t] = getframe()
% if not using cache simply call 'getframe' and done
if(cache<=0), [I,t]=r('getframe',s); return; end
% if cache initialized and frame in cache perform lookup
f=r('getinfo',s); f=f.curFrame; i=find(f==fs,1);
if(i), as=as+1; as(i)=0; t=ts(i); I=Is(inds{:},i); return; end
% if image not in cache add (and possibly initialize)
[I,t]=r('getframe',s); if(0), fprintf('reading frame %i\n',f); end
if(isempty(Is)), Is=zeros([size(I) cache],class(I));
as=ones(1,cache); fs=-as; ts=as; inds=repmat({':'},1,ndims(I)); end
[~,i]=max(as); as(i)=0; fs(i)=f; ts(i)=t; Is(inds{:},i)=I;
end
end
function sw = writer( fName, info )
% Create interface sw for writing seq files.
%
% Create interface sw to seq file with the following commands:
% sw.close(); % Close seq file (sw is useless after).
% sw.addframe(I,[ts]); % Writes video frame (and timestamp)
% sw.addframeb(bytes); % Writes video frame with no encoding.
% info = sw.getinfo(); % Return struct with info about video.
%
% The following params must be specified in struct 'info' upon opening:
% width - frame width
% height - frame height
% fps - frames per second
% quality - [80] compression quality (0 to 100)
% codec - string representing codec, options include:
% 'monoraw'/'imageFormat100' - black/white uncompressed
% 'raw'/'imageFormat200' - color (BGR) uncompressed
% 'monojpg'/'imageFormat102' - black/white jpg compressed
% 'jpg'/'imageFormat201' - color jpg compressed
% 'monopng'/'imageFormat001' - black/white png compressed
% 'png'/'imageFormat002' - color png compressed
%
% USAGE
% sw = seqIo( fName, 'writer', info )
%
% INPUTS
% fName - seq file name
% info - see above
%
% OUTPUTS
% sw - interface for writing seq file
%
% EXAMPLE
%
% See also seqIo, seqWriterPlugin
w=@seqWriterPlugin; s=w('open',int32(-1),fName,info);
sw = struct( 'close',@() w('close',s), 'getinfo',@() w('getinfo',s), ...
'addframe',@(varargin) w('addframe',s,varargin{:}), ...
'addframeb',@(varargin) w('addframeb',s,varargin{:}) );
end
function info = getInfo( fName )
% Get info about seq file.
%
% USAGE
% info = seqIo( fName, 'getInfo' )
%
% INPUTS
% fName - seq file name
%
% OUTPUTS
% info - information struct
%
% EXAMPLE
%
% See also seqIo
sr=reader(fName); info=sr.getinfo(); sr.close();
end
function crop( fName, tName, frames )
% Crop sub-sequence from seq file.
%
% Frame indices are 0 indexed. frames need not be consecutive and can
% contain duplicates. An index of -1 indicates a blank (all 0) frame. If
% contiguous subset of frames is cropped timestamps are preserved.
%
% USAGE
% seqIo( fName, 'crop', tName, frames )
%
% INPUTS
% fName - seq file name
% tName - cropped seq file name
% frames - frame indices (0 indexed)
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo
sr=reader(fName); info=sr.getinfo(); sw=writer(tName,info);
frames=frames(:)'; pad=sr.getnext(); pad(:)=0;
kp=frames>=0 & frames<info.numFrames; if(~all(kp)), frames=frames(kp);
warning('piotr:seqIo:crop','%i out of bounds frames',sum(~kp)); end
ordered=all(frames(2:end)==frames(1:end-1)+1);
n=length(frames); k=0; tid=ticStatus;
for f=frames
if(f<0), sw.addframe(pad); continue; end
sr.seek(f); [I,ts]=sr.getframeb(); k=k+1; tocStatus(tid,k/n);
if(ordered), sw.addframeb(I,ts); else sw.addframeb(I); end
end; sw.close(); sr.close();
end
function Is = toImgs( fName, tDir, skip, f0, f1, ext )
% Extract images from seq file to target directory or array.
%
% USAGE
% Is = seqIo( fName, 'toImgs', [tDir], [skip], [f0], [f1], [ext] )
%
% INPUTS
% fName - seq file name
% tDir - [] target directory (if empty extract images to array)
% skip - [1] skip between written frames
% f0 - [0] first frame to write
% f1 - [numFrames-1] last frame to write
% ext - [] optionally save as given type (slow, reconverts)
%
% OUTPUTS
% Is - if isempty(tDir) outputs image array (else Is=[])
%
% EXAMPLE
%
% See also seqIo
if(nargin<2 || isempty(tDir)), tDir=[]; end
if(nargin<3 || isempty(skip)), skip=1; end
if(nargin<4 || isempty(f0)), f0=0; end
if(nargin<5 || isempty(f1)), f1=inf; end
if(nargin<6 || isempty(ext)), ext=''; end
sr=reader(fName); info=sr.getinfo(); f1=min(f1,info.numFrames-1);
frames=f0:skip:f1; n=length(frames); tid=ticStatus; k=0;
% output images to array
if(isempty(tDir))
I=sr.getnext(); d=ndims(I); assert(d==2 || d==3);
try Is=zeros([size(I) n],class(I)); catch e; sr.close(); throw(e); end
for k=1:n, sr.seek(frames(k)); I=sr.getframe(); tocStatus(tid,k/n);
if(d==2), Is(:,:,k)=I; else Is(:,:,:,k)=I; end; end
sr.close(); return;
end
% output images to directory
if(~exist(tDir,'dir')), mkdir(tDir); end; Is=[];
for frame=frames
f=[tDir '/I' int2str2(frame,5) '.']; sr.seek(frame);
if(~isempty(ext)), I=sr.getframe(); imwrite(I,[f ext]); else
I=sr.getframeb(); f=fopen([f info.ext],'w');
if(f<=0), sr.close(); assert(false); end
fwrite(f,I); fclose(f);
end; k=k+1; tocStatus(tid,k/n);
end; sr.close();
end
function frImgs( fName, info, varargin )
% Create seq file from an array or directory of images or from an AVI file.
%
% For info, if converting from array, only codec (e.g., 'jpg') and fps must
% be specified while width and height and determined automatically. If
% converting from AVI, fps is also determined automatically.
%
% USAGE
% seqIo( fName, 'frImgs', info, varargin )
%
% INPUTS
% fName - seq file name
% info - defines codec, etc, see seqIo>writer
% varargin - additional params (struct or name/value pairs)
% .aviName - [] if specified create seq from avi file
% .Is - [] if specified create seq from image array
% .sDir - [] source directory
% .skip - [1] skip between frames
% .name - ['I'] base name of images
% .nDigits - [5] number of digits for filename index
% .f0 - [0] first frame to read
% .f1 - [10^6] last frame to read
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo, seqIo>writer
dfs={'aviName','','Is',[],'sDir',[],'skip',1,'name','I',...
'nDigits',5,'f0',0,'f1',10^6};
[aviName,Is,sDir,skip,name,nDigits,f0,f1] ...
= getPrmDflt(varargin,dfs,1);
if(~isempty(aviName))
if(exist('mmread.m','file')==2) % use external mmread function
% mmread requires full pathname, which is obtained via 'which'. But,
% 'which' can fail (maltab bug), so best to just pass in full pathname
t=which(aviName); if(~isempty(t)), aviName=t; end
V=mmread(aviName); n=V.nrFramesTotal;
info.height=V.height; info.width=V.width; info.fps=V.rate;
sw=writer(fName,info); tid=ticStatus('creating seq from avi');
for f=1:n, sw.addframe(V.frames(f).cdata); tocStatus(tid,f/n); end
sw.close();
else % use matlab mmreader function
emsg=['mmreader.m failed to load video. In general mmreader.m is ' ...
'known to have many issues, especially on Linux. I suggest ' ...
'installing the similarly named mmread toolbox from Micah ' ...
'Richert, available at Matlab Central. If mmread is installed, ' ...
'seqIo will automatically use mmread instead of mmreader.'];
try V=mmreader(aviName); catch %#ok<DMMR,CTCH>
error('piotr:seqIo:frImgs',emsg); end; n=V.NumberOfFrames;
info.height=V.Height; info.width=V.Width; info.fps=V.FrameRate;
sw=writer(fName,info); tid=ticStatus('creating seq from avi');
for f=1:n, sw.addframe(read(V,f)); tocStatus(tid,f/n); end
sw.close();
end
elseif( isempty(Is) )
assert(exist(sDir,'dir')==7); sw=writer(fName,info); info=sw.getinfo();
frmStr=sprintf('%s/%s%%0%ii.%s',sDir,name,nDigits,info.ext);
for frame = f0:skip:f1
f=sprintf(frmStr,frame); if(~exist(f,'file')), break; end
f=fopen(f,'r'); if(f<=0), sw.close(); assert(false); end
I=fread(f); fclose(f); sw.addframeb(I);
end; sw.close();
if(frame==f0), warning('No images found.'); end %#ok<WNTAG>
else
nd=ndims(Is); if(nd==2), nd=3; end; assert(nd<=4); nFrm=size(Is,nd);
info.height=size(Is,1); info.width=size(Is,2); sw=writer(fName,info);
if(nd==3), for f=1:nFrm, sw.addframe(Is(:,:,f)); end; end
if(nd==4), for f=1:nFrm, sw.addframe(Is(:,:,:,f)); end; end
sw.close();
end
end
function convert( fName, tName, imgFun, varargin )
% Convert seq file by applying imgFun(I) to each frame I.
%
% USAGE
% seqIo( fName, 'convert', tName, imgFun, varargin )
%
% INPUTS
% fName - seq file name
% tName - converted seq file name
% imgFun - function to apply to each image
% varargin - additional params (struct or name/value pairs)
% .info - [] info for target seq file
% .skip - [1] skip between frames
% .f0 - [0] first frame to read
% .f1 - [inf] last frame to read
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo
dfs={'info',[],'skip',1,'f0',0,'f1',inf};
[info,skip,f0,f1]=getPrmDflt(varargin,dfs,1);
assert(~strcmp(tName,fName)); sr=reader(fName); infor=sr.getinfo();
if(isempty(info)), info=infor; end; n=infor.numFrames; f1=min(f1,n-1);
I=sr.getnext(); I=imgFun(I); info.width=size(I,2); info.height=size(I,1);
sw=writer(tName,info); tid=ticStatus('converting seq');
frames=f0:skip:f1; n=length(frames); k=0;
for f=frames, sr.seek(f); [I,ts]=sr.getframe(); I=imgFun(I);
if(skip==1), sw.addframe(I,ts); else sw.addframe(I); end
k=k+1; tocStatus(tid,k/n);
end; sw.close(); sr.close();
end
function newHeader( fName, info )
% Replace header of seq file with provided info.
%
% Can be used if the file fName has a corrupt header. Automatically tries
% to compute number of frames in fName. No guarantees that it will work.
%
% USAGE
% seqIo( fName, 'newHeader', info )
%
% INPUTS
% fName - seq file name
% info - info for target seq file
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo
[d,n]=fileparts(fName); if(isempty(d)), d='.'; end
fName=[d '/' n]; tName=[fName '-new' datestr(now,30)];
if(exist([fName '-seek.mat'],'file')); delete([fName '-seek.mat']); end
srp=@seqReaderPlugin; hr=srp('open',int32(-1),fName,info); tid=ticStatus;
info=srp('getinfo',hr); sw=writer(tName,info); n=info.numFrames;
for f=1:n, srp('next',hr); [I,ts]=srp('getframeb',hr);
sw.addframeb(I,ts); tocStatus(tid,f/n); end
srp('close',hr); sw.close();
end
function sr = readerDual( fNames, cache )
% Create interface sr for reading dual seq files.
%
% Wrapper for two seq files of the same image dims and roughly the same
% frame counts that are treated as a single reader object. getframe()
% returns the concatentation of the two frames. For videos of different
% frame counts, the first video serves as the "dominant" video and the
% frame count of the second video is adjusted accordingly. Same general
% usage as in reader, but the only supported operations are: close(),
% getframe(), getinfo(), and seek().
%
% USAGE
% sr = seqIo( fNames, 'readerDual', [cache] )
%
% INPUTS
% fNames - two seq file names
% cache - [0] size of cache (see seqIo>reader)
%
% OUTPUTS
% sr - interface for reading seq file
%
% EXAMPLE
%
% See also seqIo, seqIo>reader
if(nargin<2 || isempty(cache)), cache=0; end
s1=reader(fNames{1}, cache); i1=s1.getinfo();
s2=reader(fNames{2}, cache); i2=s2.getinfo();
info=i1; info.width=i1.width+i2.width;
if( i1.width~=i2.width || i1.height~=i2.height )
s1.close(); s2.close(); error('Mismatched videos'); end
if( i1.numFrames~=i2.numFrames )
warning('seq files of different lengths'); end %#ok<WNTAG>
frame2=@(f) round(f/(i1.numFrames-1)*(i2.numFrames-1));
sr=struct('close',@() min(s1.close(),s2.close()), ...
'getframe',@getframe, 'getinfo',@() info, ...
'seek',@(f) s1.seek(f) & s2.seek(frame2(f)) );
function [I,t] = getframe()
[I1,t]=s1.getframe(); I2=s2.getframe(); I=[I1 I2]; end
end
|
github
|
3arbouch/PersonDetection-master
|
seqReaderPlugin.m
|
.m
|
PersonDetection-master/Source/toolbox/videos/seqReaderPlugin.m
| 9,617 |
utf_8
|
ad8f912634cafe13df6fc7d67aeff05a
|
function varargout = seqReaderPlugin( cmd, h, varargin )
% Plugin for seqIo and videoIO to allow reading of seq files.
%
% Do not call directly, use as plugin for seqIo or videoIO instead.
% The following is a list of commands available (srp=seqReaderPlugin):
% h = srp('open',h,fName) % Open a seq file for reading (h ignored).
% h = srp('close',h); % Close seq file (output h is -1).
% [I,ts] =srp('getframe',h) % Get current frame (returns [] if invalid).
% [I,ts] =srp('getframeb',h) % Get current frame with no decoding.
% ts = srp('getts',h) % Return timestamps for all frames.
% info = srp('getinfo',h) % Return struct with info about video.
% [I,ts] =srp('getnext',h) % Shortcut for 'next' followed by 'getframe'.
% out = srp('next',h) % Go to next frame (out=0 on fail).
% out = srp('seek',h,frame) % Go to specified frame (out=0 on fail).
% out = srp('step',h,delta) % Go to current frame+delta (out=0 on fail).
%
% USAGE
% varargout = seqReaderPlugin( cmd, h, varargin )
%
% INPUTS
% cmd - string indicating operation to perform
% h - unique identifier for open seq file
% varargin - additional options (vary according to cmd)
%
% OUTPUTS
% varargout - output (varies according to cmd)
%
% EXAMPLE
%
% See also SEQIO, SEQWRITERPLUGIN
%
% Piotr's Computer Vision Matlab Toolbox Version 3.10
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% persistent variables to keep track of all loaded .seq files
persistent h1 hs cs fids infos tNms;
if(isempty(h1)), h1=int32(now); hs=int32([]); infos={}; tNms={}; end
nIn=nargin-2; in=varargin; o2=[]; cmd=lower(cmd);
% open seq file
if(strcmp(cmd,'open'))
chk(nIn,1,2); h=length(hs)+1; hs(h)=h1; varargout={h1}; h1=h1+1;
[pth,name]=fileparts(in{1}); if(isempty(pth)), pth='.'; end
if(nIn==1), info=[]; else info=in{2}; end
fName=[pth filesep name]; cs(h)=-1;
[infos{h},fids(h),tNms{h}]=open(fName,info); return;
end
% Get the handle for this instance
[v,h]=ismember(h,hs); if(~v), error('Invalid load plugin handle'); end
c=cs(h); fid=fids(h); info=infos{h}; tNm=tNms{h};
% close seq file
if(strcmp(cmd,'close'))
chk(nIn,0); varargout={-1}; fclose(fid); kp=[1:h-1 h+1:length(hs)];
hs=hs(kp); cs=cs(kp); fids=fids(kp); infos=infos(kp);
tNms=tNms(kp); if(exist(tNm,'file')), delete(tNm); end; return;
end
% perform appropriate operation
switch( cmd )
case 'getframe', chk(nIn,0); [o1,o2]=getFrame(c,fid,info,tNm,1);
case 'getframeb', chk(nIn,0); [o1,o2]=getFrame(c,fid,info,tNm,0);
case 'getts', chk(nIn,0); o1=getTs(0:info.numFrames-1,fid,info);
case 'getinfo', chk(nIn,0); o1=info; o1.curFrame=c;
case 'getnext', chk(nIn,0); c=c+1; [o1,o2]=getFrame(c,fid,info,tNm,1);
case 'next', chk(nIn,0); [c,o1]=valid(c+1,info);
case 'seek', chk(nIn,1); [c,o1]=valid(in{1},info);
case 'step', chk(nIn,1); [c,o1]=valid(c+in{1},info);
otherwise, error(['Unrecognized command: "' cmd '"']);
end
cs(h)=c; varargout={o1,o2};
end
function chk(nIn,nMin,nMax)
if(nargin<3), nMax=nMin; end
if(nIn>0 && nMin==0 && nMax==0), error(['"' cmd '" takes no args.']); end
if(nIn<nMin||nIn>nMax), error(['Incorrect num args for "' cmd '".']); end
end
function success = getImgFile( fName )
% create local copy of fName which is in a imagesci/private
fName = [fName '.' mexext]; s = filesep; success = 1;
sName = [fileparts(which('imread.m')) s 'private' s fName];
tName = [fileparts(mfilename('fullpath')) s 'private' s fName];
if(~exist(tName,'file')), success=copyfile(sName,tName); end
end
function [info, fid, tNm] = open( fName, info )
% open video for reading, get header
if(exist([fName '.seq'],'file')==0)
error('seq file not found: %s.seq',fName); end
fid=fopen([fName '.seq'],'r','l');
if(isempty(info)), info=readHeader(fid); else
info.numFrames=0; fseek(fid,1024,'bof'); end
switch(info.imageFormat)
case {100,200}, ext='raw';
case {101 }, ext='brgb8';
case {102,201}, ext='jpg';
case {103 }, ext ='jbrgb';
case {001,002}, ext='png';
otherwise, error('unknown format');
end; info.ext=ext; s=1;
if(any(strcmp(ext,{'jpg','jbrgb'}))), s=getImgFile('rjpg8c'); end
if(strcmp(ext,'png')), s=getImgFile('png');
if(s), info.readImg=@(nm) png('read',nm,[]); end; end
if(strcmp(ext,'png') && ~s), s=getImgFile('pngreadc');
if(s), info.readImg=@(nm) pngreadc(nm,[],false); end; end
if(~s), error('Cannot find Matlab''s source image reader'); end
% generate unique temporary name
[~,tNm]=fileparts(fName); t=clock; t=mod(t(end),1);
tNm=sprintf('tmp_%s_%15i.%s',tNm,round((t+rand)/2*1e15),ext);
% compute seek info for compressed images
if(any(strcmp(ext,{'raw','brgb8'}))), assert(info.numFrames>0); else
oName=[fName '-seek.mat']; n=info.numFrames; if(n==0), n=10^7; end
if(exist(oName,'file')==2), load(oName); info.seek=seek; else %#ok<NODEF>
tid=ticStatus('loading seek info',.1,5); seek=zeros(n,1); seek(1)=1024;
extra=8; % extra bytes after image data (8 for ts, then 0 or 8 empty)
for i=2:n
s=seek(i-1)+fread(fid,1,'uint32')+extra; valid=fseek(fid,s,'bof')==0;
if(i==2 && valid), if(fread(fid,1,'uint32')~=0), fseek(fid,-4,'cof');
else extra=extra+8; s=s+8; valid=fseek(fid,s,'bof')==0; end; end
if(valid), seek(i)=s; tocStatus(tid,i/n);
else n=i-1; seek=seek(1:n); tocStatus(tid,1); break; end
end; if(info.numFrames==0), info.numFrames=n; end
try save(oName,'seek'); catch; end; info.seek=seek; %#ok<CTCH>
end
end
% compute frame rate from timestamps as stored fps may be incorrect
n=min(100,info.numFrames); if(n==1), return; end
ts = getTs( 0:(n-1), fid, info );
ds=ts(2:end)-ts(1:end-1); ds=ds(abs(ds-median(ds))<.005);
if(~isempty(ds)), info.fps=1/mean(ds); end
end
function [frame,v] = valid( frame, info )
v=(frame>=0 && frame<info.numFrames);
end
function [I,ts] = getFrame( frame, fid, info, tNm, decode )
% get frame image (I) and timestamp (ts) at which frame was recorded
nCh=info.imageBitDepth/8; ext=info.ext;
if(frame<0 || frame>=info.numFrames), I=[]; ts=[]; return; end
switch ext
case {'raw','brgb8'}
% read in an uncompressed image (assume imageBitDepthReal==8)
fseek(fid,1024+frame*info.trueImageSize,'bof');
I = fread(fid,info.imageSizeBytes,'*uint8');
if( decode )
% reshape appropriately for mxn or mxnx3 RGB image
siz = [info.height info.width nCh];
if(nCh==1), I=reshape(I,siz(2),siz(1))'; else
I = permute(reshape(I,siz(3),siz(2),siz(1)),[3,2,1]);
end
if(nCh==3), t=I(:,:,3); I(:,:,3)=I(:,:,1); I(:,:,1)=t; end
if(strcmp(ext,'brgb8')), I=demosaic(I,'bggr'); end
end
case {'jpg','jbrgb'}
fseek(fid,info.seek(frame+1),'bof'); nBytes=fread(fid,1,'uint32');
I = fread(fid,nBytes-4,'*uint8');
if( decode )
% write/read to/from temporary .jpg (not that much overhead)
assert(I(1)==255 && I(2)==216 && I(end-1)==255 && I(end)==217); % JPG
for t=0:99, fw=fopen(tNm,'w'); if(fw>=0), break; end; pause(.01); end
if(fw==-1), error(['unable to write: ' tNm]); end
fwrite(fw,I); fclose(fw); I=rjpg8c(tNm);
if(strcmp(ext,'jbrgb')), I=demosaic(I,'bggr'); end
end
case 'png'
fseek(fid,info.seek(frame+1),'bof'); nBytes=fread(fid,1,'uint32');
I = fread(fid,nBytes-4,'*uint8');
if( decode )
% write/read to/from temporary .png (not that much overhead)
for t=0:99, fw=fopen(tNm,'w'); if(fw>=0), break; end; pause(.01); end
if(fw==-1), error(['unable to write: ' tNm]); end
fwrite(fw,I); fclose(fw); I=info.readImg(tNm);
I=permute(I,ndims(I):-1:1);
end
otherwise, assert(false);
end
if(nargout==2), ts=fread(fid,1,'uint32')+fread(fid,1,'uint16')/1000; end
end
function ts = getTs( frames, fid, info )
% get timestamps (ts) at which frames were recorded
n=length(frames); ts=nan(1,n);
for i=1:n, frame=frames(i);
if(frame<0 || frame>=info.numFrames), continue; end
switch info.ext
case {'raw','brgb8'} % uncompressed
fseek(fid,1024+frame*info.trueImageSize+info.imageSizeBytes,'bof');
case {'jpg','png','jbrgb'} % compressed
fseek(fid,info.seek(frame+1),'bof');
fseek(fid,fread(fid,1,'uint32')-4,'cof');
otherwise, assert(false);
end
ts(i)=fread(fid,1,'uint32')+fread(fid,1,'uint16')/1000;
end
end
function info = readHeader( fid )
% see streampix manual for info on header
fseek(fid,0,'bof');
% check that header is not all 0's (a common error)
[tmp,n]=fread(fid,1024); if(n<1024), error('no header'); end
if(all(tmp==0)), error('fully empty header'); end; fseek(fid,0,'bof');
% first 4 bytes store OxFEED, next 24 store 'Norpix seq '
if( ~strcmp(sprintf('%X',fread(fid,1,'uint32')),'FEED') || ...
~strcmp(char(fread(fid,10,'uint16'))','Norpix seq') ) %#ok<FREAD>
error('invalid header');
end; fseek(fid,4,'cof');
% next 8 bytes for version and header size (1024), then 512 for descr
version=fread(fid,1,'int32'); assert(fread(fid,1,'uint32')==1024);
descr=char(fread(fid,256,'uint16'))'; %#ok<FREAD>
% read in more info
tmp=fread(fid,9,'uint32'); assert(tmp(8)==0);
fps = fread(fid,1,'float64'); codec=['imageFormat' int2str2(tmp(6),3)];
% store information in info struct
info=struct( 'width',tmp(1), 'height',tmp(2), 'imageBitDepth',tmp(3), ...
'imageBitDepthReal',tmp(4), 'imageSizeBytes',tmp(5), ...
'imageFormat',tmp(6), 'numFrames',tmp(7), 'trueImageSize', tmp(9),...
'fps',fps, 'seqVersion',version, 'codec',codec, 'descr',descr, ...
'nHiddenFinalFrames',0 );
assert(info.imageBitDepthReal==8);
% seek to end of header
fseek(fid,432,'cof');
end
|
github
|
3arbouch/PersonDetection-master
|
pcaApply.m
|
.m
|
PersonDetection-master/Source/toolbox/classify/pcaApply.m
| 3,320 |
utf_8
|
a06fc0e54d85930cbc0536c874ac63b7
|
function varargout = pcaApply( X, U, mu, k )
% Companion function to pca.
%
% Use pca.m to retrieve the principal components U and the mean mu from a
% set of vectors x, then use pcaApply to get the first k coefficients of
% x in the space spanned by the columns of U. See pca for general usage.
%
% If x is large, pcaApply first splits and processes x in parts. This
% allows pcaApply to work even for very large arrays.
%
% This may prove useful:
% siz=size(X); k=100; Uim=reshape(U(:,1:k),[siz(1:end-1) k ]);
%
% USAGE
% [ Yk, Xhat, avsq ] = pcaApply( X, U, mu, k )
%
% INPUTS
% X - data for which to get PCA coefficients
% U - returned by pca.m
% mu - returned by pca.m
% k - number of principal coordinates to approximate X with
%
% OUTPUTS
% Yk - first k coordinates of X in column space of U
% Xhat - approximation of X corresponding to Yk
% avsq - measure of squared error normalized to fall between [0,1]
%
% EXAMPLE
%
% See also PCA, PCAVISUALIZE
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% sizes / dimensions
siz = size(X); nd = ndims(X); [D,r] = size(U);
if(D==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
n = siz(end);
% some error checking
if(prod(siz(1:end-1))~=D); error('incorrect size for X or U'); end
if(isa(X,'uint8')); X = double(X); end
if(k>r); warning(['k set to ' int2str(r)]); k=r; end; %#ok<WNTAG>
% If X is small simply call pcaApply1 once.
% OW break up X and call pcaApply1 multiple times and recombine.
maxWidth = ceil( (10^7) / D );
if( maxWidth > n )
varargout = cell(1,nargout);
[varargout{:}] = pcaApply1( X, U, mu, k );
else
inds = {':'}; inds = inds(:,ones(1,nd-1));
Yk = zeros( k, n ); Xhat = zeros( siz );
avsq = 0; avsqOrig = 0; last = 0;
if( nargout==3 ); out=cell(1,4); else out=cell(1,nargout); end;
while(last < n)
first=last+1; last=min(first+maxWidth-1,n);
Xi = X(inds{:}, first:last);
[out{:}] = pcaApply1( Xi, U, mu, k );
Yk(:,first:last) = out{1};
if( nargout>=2 ); Xhat(inds{:},first:last)=out{2}; end;
if( nargout>=3 ); avsq=avsq+out{3}; avsqOrig=avsqOrig+out{4}; end;
end;
varargout = {Yk, Xhat, avsq/avsqOrig};
end
function [ Yk, Xhat, avsq, avsqOrig ] = pcaApply1( X, U, mu, k )
% sizes / dimensions
siz = size(X); nd = ndims(X); [D,r] = size(U);
if(D==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
n = siz(end);
% subtract mean, then flatten X
Xorig = X;
muRep = repmat(mu, [ones(1,nd-1), n ] );
X = X - muRep;
X = reshape( X, D, n );
% Find Yk, the first k coefficients of X in the new basis
if( r<=k ); Uk=U; else Uk=U(:,1:k); end;
Yk = Uk' * X;
% calculate Xhat - the approx of X using the first k princ components
if( nargout>1 )
Xhat = Uk * Yk;
Xhat = reshape( Xhat, siz );
Xhat = Xhat + muRep;
end
% caclulate average value of (Xhat-Xorig).^2 compared to average value
% of X.^2, where X is Xorig without the mean. This is equivalent to
% what fraction of the variance is captured by Xhat.
if( nargout>2 )
avsq = Xhat - Xorig;
avsq = dot(avsq(:),avsq(:));
avsqOrig = dot(X(:),X(:));
if( nargout==3 ); avsq=avsq/avsqOrig; end
end
|
github
|
3arbouch/PersonDetection-master
|
forestTrain.m
|
.m
|
PersonDetection-master/Source/toolbox/classify/forestTrain.m
| 6,138 |
utf_8
|
de534e2a010f452a7b13167dbf9df239
|
function forest = forestTrain( data, hs, varargin )
% Train random forest classifier.
%
% Dimensions:
% M - number trees
% F - number features
% N - number input vectors
% H - number classes
%
% USAGE
% forest = forestTrain( data, hs, [varargin] )
%
% INPUTS
% data - [NxF] N length F feature vectors
% hs - [Nx1] or {Nx1} target output labels in [1,H]
% varargin - additional params (struct or name/value pairs)
% .M - [1] number of trees to train
% .H - [max(hs)] number of classes
% .N1 - [5*N/M] number of data points for training each tree
% .F1 - [sqrt(F)] number features to sample for each node split
% .split - ['gini'] options include 'gini', 'entropy' and 'twoing'
% .minCount - [1] minimum number of data points to allow split
% .minChild - [1] minimum number of data points allowed at child nodes
% .maxDepth - [64] maximum depth of tree
% .dWts - [] weights used for sampling and weighing each data point
% .fWts - [] weights used for sampling features
% .discretize - [] optional function mapping structured to class labels
% format: [hsClass,hBest] = discretize(hsStructured,H);
%
% OUTPUTS
% forest - learned forest model struct array w the following fields
% .fids - [Kx1] feature ids for each node
% .thrs - [Kx1] threshold corresponding to each fid
% .child - [Kx1] index of child for each node
% .distr - [KxH] prob distribution at each node
% .hs - [Kx1] or {Kx1} most likely label at each node
% .count - [Kx1] number of data points at each node
% .depth - [Kx1] depth of each node
%
% EXAMPLE
% N=10000; H=5; d=2; [xs0,hs0,xs1,hs1]=demoGenData(N,N,H,d,1,1);
% xs0=single(xs0); xs1=single(xs1);
% pTrain={'maxDepth',50,'F1',2,'M',150,'minChild',5};
% tic, forest=forestTrain(xs0,hs0,pTrain{:}); toc
% hsPr0 = forestApply(xs0,forest);
% hsPr1 = forestApply(xs1,forest);
% e0=mean(hsPr0~=hs0); e1=mean(hsPr1~=hs1);
% fprintf('errors trn=%f tst=%f\n',e0,e1); figure(1);
% subplot(2,2,1); visualizeData(xs0,2,hs0);
% subplot(2,2,2); visualizeData(xs0,2,hsPr0);
% subplot(2,2,3); visualizeData(xs1,2,hs1);
% subplot(2,2,4); visualizeData(xs1,2,hsPr1);
%
% See also forestApply, fernsClfTrain
%
% Piotr's Computer Vision Matlab Toolbox Version 3.24
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get additional parameters and fill in remaining parameters
dfs={ 'M',1, 'H',[], 'N1',[], 'F1',[], 'split','gini', 'minCount',1, ...
'minChild',1, 'maxDepth',64, 'dWts',[], 'fWts',[], 'discretize','' };
[M,H,N1,F1,splitStr,minCount,minChild,maxDepth,dWts,fWts,discretize] = ...
getPrmDflt(varargin,dfs,1);
[N,F]=size(data); assert(length(hs)==N); discr=~isempty(discretize);
minChild=max(1,minChild); minCount=max([1 minCount minChild]);
if(isempty(H)), H=max(hs); end; assert(discr || all(hs>0 & hs<=H));
if(isempty(N1)), N1=round(5*N/M); end; N1=min(N,N1);
if(isempty(F1)), F1=round(sqrt(F)); end; F1=min(F,F1);
if(isempty(dWts)), dWts=ones(1,N,'single'); end; dWts=dWts/sum(dWts);
if(isempty(fWts)), fWts=ones(1,F,'single'); end; fWts=fWts/sum(fWts);
split=find(strcmpi(splitStr,{'gini','entropy','twoing'}))-1;
if(isempty(split)), error('unknown splitting criteria: %s',splitStr); end
% make sure data has correct types
if(~isa(data,'single')), data=single(data); end
if(~isa(hs,'uint32') && ~discr), hs=uint32(hs); end
if(~isa(fWts,'single')), fWts=single(fWts); end
if(~isa(dWts,'single')), dWts=single(dWts); end
% train M random trees on different subsets of data
prmTree = {H,F1,minCount,minChild,maxDepth,fWts,split,discretize};
for i=1:M
if(N==N1), data1=data; hs1=hs; dWts1=dWts; else
d=wswor(dWts,N1,4); data1=data(d,:); hs1=hs(d);
dWts1=dWts(d); dWts1=dWts1/sum(dWts1);
end
tree = treeTrain(data1,hs1,dWts1,prmTree);
if(i==1), forest=tree(ones(M,1)); else forest(i)=tree; end
end
end
function tree = treeTrain( data, hs, dWts, prmTree )
% Train single random tree.
[H,F1,minCount,minChild,maxDepth,fWts,split,discretize]=deal(prmTree{:});
N=size(data,1); K=2*N-1; discr=~isempty(discretize);
thrs=zeros(K,1,'single'); distr=zeros(K,H,'single');
fids=zeros(K,1,'uint32'); child=fids; count=fids; depth=fids;
hsn=cell(K,1); dids=cell(K,1); dids{1}=uint32(1:N); k=1; K=2;
while( k < K )
% get node data and store distribution
dids1=dids{k}; dids{k}=[]; hs1=hs(dids1); n1=length(hs1); count(k)=n1;
if(discr), [hs1,hsn{k}]=feval(discretize,hs1,H); hs1=uint32(hs1); end
if(discr), assert(all(hs1>0 & hs1<=H)); end; pure=all(hs1(1)==hs1);
if(~discr), if(pure), distr(k,hs1(1))=1; hsn{k}=hs1(1); else
distr(k,:)=histc(hs1,1:H)/n1; [~,hsn{k}]=max(distr(k,:)); end; end
% if pure node or insufficient data don't train split
if( pure || n1<=minCount || depth(k)>maxDepth ), k=k+1; continue; end
% train split and continue
fids1=wswor(fWts,F1,4); data1=data(dids1,fids1);
[~,order1]=sort(data1); order1=uint32(order1-1);
[fid,thr,gain]=forestFindThr(data1,hs1,dWts(dids1),order1,H,split);
fid=fids1(fid); left=data(dids1,fid)<thr; count0=nnz(left);
if( gain>1e-10 && count0>=minChild && (n1-count0)>=minChild )
child(k)=K; fids(k)=fid-1; thrs(k)=thr;
dids{K}=dids1(left); dids{K+1}=dids1(~left);
depth(K:K+1)=depth(k)+1; K=K+2;
end; k=k+1;
end
% create output model struct
K=1:K-1; if(discr), hsn={hsn(K)}; else hsn=[hsn{K}]'; end
tree=struct('fids',fids(K),'thrs',thrs(K),'child',child(K),...
'distr',distr(K,:),'hs',hsn,'count',count(K),'depth',depth(K));
end
function ids = wswor( prob, N, trials )
% Fast weighted sample without replacement. Alternative to:
% ids=datasample(1:length(prob),N,'weights',prob,'replace',false);
M=length(prob); assert(N<=M); if(N==M), ids=1:N; return; end
if(all(prob(1)==prob)), ids=randperm(M,N); return; end
cumprob=min([0 cumsum(prob)],1); assert(abs(cumprob(end)-1)<.01);
cumprob(end)=1; [~,ids]=histc(rand(N*trials,1),cumprob);
[s,ord]=sort(ids); K(ord)=[1; diff(s)]~=0; ids=ids(K);
if(length(ids)<N), ids=wswor(cumprob,N,trials*2); end
ids=ids(1:N)';
end
|
github
|
3arbouch/PersonDetection-master
|
fernsRegTrain.m
|
.m
|
PersonDetection-master/Source/toolbox/classify/fernsRegTrain.m
| 5,914 |
utf_8
|
b9ed2d87a22cb9cbb1e2632495ddaf1d
|
function [ferns,ysPr] = fernsRegTrain( data, ys, varargin )
% Train boosted fern regressor.
%
% Boosted regression using random ferns as the weak regressor. See "Greedy
% function approximation: A gradient boosting machine", Friedman, Annals of
% Statistics 2001, for more details on boosted regression.
%
% A few notes on the parameters: 'type' should in general be set to 'res'
% (the 'ave' version is an undocumented variant that only performs well
% under limited conditions). 'loss' determines the loss function being
% optimized, in general the 'L2' version is the most robust and effective.
% 'reg' is a regularization term for the ferns, a low value such as .01 can
% improve results. Setting the learning rate 'eta' is crucial in order to
% achieve good performance, especially on noisy data. In general, eta
% should decreased as M is increased.
%
% Dimensions:
% M - number ferns
% R - number repeats
% S - fern depth
% N - number samples
% F - number features
%
% USAGE
% [ferns,ysPr] = fernsRegTrain( data, hs, [varargin] )
%
% INPUTS
% data - [NxF] N length F feature vectors
% ys - [Nx1] target output values
% varargin - additional params (struct or name/value pairs)
% .type - ['res'] options include {'res','ave'}
% .loss - ['L2'] options include {'L1','L2','exp'}
% .S - [2] fern depth (ferns are exponential in S)
% .M - [50] number ferns (same as number phases)
% .R - [10] number repetitions per fern
% .thrr - [0 1] range for randomly generated thresholds
% .reg - [0.01] fern regularization term in [0,1]
% .eta - [1] learning rate in [0,1] (not used if type='ave')
% .verbose - [0] if true output info to display
%
% OUTPUTS
% ferns - learned fern model w the following fields
% .fids - [MxS] feature ids for each fern for each depth
% .thrs - [MxS] threshold corresponding to each fid
% .ysFern - [2^SxM] stored values at fern leaves
% .loss - loss(ys,ysGt) computes loss of ys relateive to ysGt
% ysPr - [Nx1] predicted output values
%
% EXAMPLE
% %% generate toy data
% N=1000; sig=.5; f=@(x) cos(x*pi*4)+(x+1).^2;
% xs0=rand(N,1); ys0=f(xs0)+randn(N,1)*sig;
% xs1=rand(N,1); ys1=f(xs1)+randn(N,1)*sig;
% %% train and apply fern regressor
% prm=struct('type','res','loss','L2','eta',.05,...
% 'thrr',[-1 1],'reg',.01,'S',2,'M',1000,'R',3,'verbose',0);
% tic, [ferns,ysPr0] = fernsRegTrain(xs0,ys0,prm); toc
% tic, ysPr1 = fernsRegApply( xs1, ferns ); toc
% fprintf('errors train=%f test=%f\n',...
% ferns.loss(ysPr0,ys0),ferns.loss(ysPr1,ys1));
% %% visualize results
% figure(1); clf; hold on; plot(xs0,ys0,'.b'); plot(xs0,ysPr0,'.r');
% figure(2); clf; hold on; plot(xs1,ys1,'.b'); plot(xs1,ysPr1,'.r');
%
% See also fernsRegApply, fernsInds
%
% Piotr's Computer Vision Matlab Toolbox Version 2.50
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get/check parameters
dfs={'type','res','loss','L2','S',2,'M',50,'R',10,'thrr',[0 1],...
'reg',0.01,'eta',1,'verbose',0};
[type,loss,S,M,R,thrr,reg,eta,verbose]=getPrmDflt(varargin,dfs,1);
type=type(1:3); assert(any(strcmp(type,{'res','ave'})));
assert(any(strcmp(loss,{'L1','L2','exp'}))); N=length(ys);
if(strcmp(type,'ave')), eta=1; end
% train stagewise regressor (residual or average)
fids=zeros(M,S,'uint32'); thrs=zeros(M,S);
ysSum=zeros(N,1); ysFern=zeros(2^S,M);
for m=1:M
% train R random ferns using different losses, keep best
if(strcmp(type,'ave')), d=m; else d=1; end
ysTar=d*ys-ysSum; best={};
if(strcmp(loss,'L1')), e=sum(abs(ysTar));
for r=1:R
[fids1,thrs1,ysFern1,ys1]=trainFern(data,sign(ysTar),S,thrr,reg);
a=medianw(ysTar./ys1,abs(ys1)); ysFern1=ysFern1*a; ys1=ys1*a;
e1=sum(abs(ysTar-ys1));
if(e1<=e), e=e1; best={fids1,thrs1,ysFern1,ys1}; end
end
elseif(strcmp(loss,'L2')), e=sum(ysTar.^2);
for r=1:R
[fids1,thrs1,ysFern1,ys1]=trainFern(data,ysTar,S,thrr,reg);
e1=sum((ysTar-ys1).^2);
if(e1<=e), e=e1; best={fids1,thrs1,ysFern1,ys1}; end
end
elseif(strcmp(loss,'exp')), e=sum(exp(ysTar/d)+exp(-ysTar/d));
ysDeriv=exp(ysTar/d)-exp(-ysTar/d);
for r=1:R
[fids1,thrs1,ysFern1,ys1]=trainFern(data,ysDeriv,S,thrr,reg);
e1=inf; if(m==1), aBst=1; end; aMin=aBst/5; aMax=aBst*5;
for phase=1:3, aDel=(aMax-aMin)/10;
for a=aMin:aDel:aMax
eTmp=sum(exp((ysTar-a*ys1)/d)+exp((a*ys1-ysTar)/d));
if(eTmp<e1), a1=a; e1=eTmp; end
end; aMin=a1-aDel; aMax=a1+aDel;
end; ysFern1=ysFern1*a1; ys1=ys1*a1;
if(e1<=e), e=e1; aBst=a1; best={fids1,thrs1,ysFern1,ys1}; end
end
end
% store results and update sums
assert(~isempty(best)); [fids1,thrs1,ysFern1,ys1]=deal(best{:});
fids(m,:)=fids1; thrs(m,:)=thrs1;
ysFern(:,m)=ysFern1*eta; ysSum=ysSum+ys1*eta;
if(verbose), fprintf('phase=%i error=%f\n',m,e); end
end
% create output struct
if(strcmp(type,'ave')), d=M; else d=1; end; clear data;
ferns=struct('fids',fids,'thrs',thrs,'ysFern',ysFern/d); ysPr=ysSum/d;
switch loss
case 'L1', ferns.loss=@(ys,ysGt) mean(abs(ys-ysGt));
case 'L2', ferns.loss=@(ys,ysGt) mean((ys-ysGt).^2);
case 'exp', ferns.loss=@(ys,ysGt) mean(exp(ys-ysGt)+exp(ysGt-ys))-2;
end
end
function [fids,thrs,ysFern,ysPr] = trainFern( data, ys, S, thrr, reg )
% Train single random fern regressor.
[N,F]=size(data); mu=sum(ys)/N; ys=ys-mu;
fids = uint32(floor(rand(1,S)*F+1));
thrs = rand(1,S)*(thrr(2)-thrr(1))+thrr(1);
inds = fernsInds(data,fids,thrs);
ysFern=zeros(2^S,1); cnts=zeros(2^S,1);
for n=1:N, ind=inds(n);
ysFern(ind)=ysFern(ind)+ys(n);
cnts(ind)=cnts(ind)+1;
end
ysFern = ysFern ./ max(cnts+reg*N,eps) + mu;
ysPr = ysFern(inds);
end
function m = medianw(x,w)
% Compute weighted median of x.
[x,ord]=sort(x(:)); w=w(ord);
[~,ind]=max(cumsum(w)>=sum(w)/2);
m = x(ind);
end
|
github
|
3arbouch/PersonDetection-master
|
rbfDemo.m
|
.m
|
PersonDetection-master/Source/toolbox/classify/rbfDemo.m
| 2,929 |
utf_8
|
14cc64fb77bcac3edec51cf6b84ab681
|
function rbfDemo( dataType, noiseSig, scale, k, cluster, show )
% Demonstration of rbf networks for regression.
%
% See rbfComputeBasis for discussion of rbfs.
%
% USAGE
% rbfDemo( dataType, noiseSig, scale, k, cluster, show )
%
% INPUTS
% dataType - 0: 1D sinusoid
% 1: 2D sinusoid
% 2: 2D stretched sinusoid
% noiseSig - std of idd gaussian noise
% scale - see rbfComputeBasis
% k - see rbfComputeBasis
% cluster - see rbfComputeBasis
% show - figure to use for display (no display if == 0)
%
% OUTPUTS
%
% EXAMPLE
% rbfDemo( 0, .2, 2, 5, 0, 1 );
% rbfDemo( 1, .2, 2, 50, 0, 3 );
% rbfDemo( 2, .2, 5, 50, 0, 5 );
%
% See also RBFCOMPUTEBASIS, RBFCOMPUTEFTRS
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%%% generate trn/tst data
if( 1 )
[Xtrn,ytrn] = rbfToyData( 500, noiseSig, dataType );
[Xtst,ytst] = rbfToyData( 100, noiseSig, dataType );
end;
%%% trn/apply rbfs
rbfBasis = rbfComputeBasis( Xtrn, k, cluster, scale, show );
rbfWeight = rbfComputeFtrs(Xtrn,rbfBasis) \ ytrn;
yTrnRes = rbfComputeFtrs(Xtrn,rbfBasis) * rbfWeight;
yTstRes = rbfComputeFtrs(Xtst,rbfBasis) * rbfWeight;
%%% get relative errors
fracErrorTrn = sum((ytrn-yTrnRes).^2) / sum(ytrn.^2);
fracErrorTst = sum((ytst-yTstRes).^2) / sum(ytst.^2);
%%% display output
display(fracErrorTst);
display(fracErrorTrn);
display(rbfBasis);
%%% visualize surface
minX = min([Xtrn; Xtst],[],1); maxX = max([Xtrn; Xtst],[],1);
if( size(Xtrn,2)==1 )
xs = linspace( minX, maxX, 1000 )';
ys = rbfComputeFtrs(xs,rbfBasis) * rbfWeight;
figure(show+1); clf; hold on; plot( xs, ys );
plot( Xtrn, ytrn, '.b' ); plot( Xtst, ytst, '.r' );
elseif( size(Xtrn,2)==2 )
xs1 = linspace(minX(1),maxX(1),25);
xs2 = linspace(minX(2),maxX(2),25);
[xs1,xs2] = ndgrid( xs1, xs2 );
ys = rbfComputeFtrs([xs1(:) xs2(:)],rbfBasis) * rbfWeight;
figure(show+1); clf; surf( xs1, xs2, reshape(ys,size(xs1)) ); hold on;
plot3( Xtrn(:,1), Xtrn(:,2), ytrn, '.b' );
plot3( Xtst(:,1), Xtst(:,2), ytst, '.r' );
end
function [X,y] = rbfToyData( N, noiseSig, dataType )
% Toy data for rbfDemo.
%
% USAGE
% [X,y] = rbfToyData( N, noiseSig, dataType )
%
% INPUTS
% N - number of points
% dataType - 0: 1D sinusoid
% 1: 2D sinusoid
% 2: 2D stretched sinusoid
% noiseSig - std of idd gaussian noise
%
% OUTPUTS
% X - [N x d] N points of d dimensions each
% y - [1 x N] value at example i
%%% generate data
if( dataType==0 )
X = rand( N, 1 ) * 10;
y = sin( X );
elseif( dataType==1 )
X = rand( N, 2 ) * 10;
y = sin( X(:,1)+X(:,2) );
elseif( dataType==2 )
X = rand( N, 2 ) * 10;
y = sin( X(:,1)+X(:,2) );
X(:,2) = X(:,2) * 5;
else
error('unknown dataType');
end
y = y + randn(size(y))*noiseSig;
|
github
|
3arbouch/PersonDetection-master
|
pdist2.m
|
.m
|
PersonDetection-master/Source/toolbox/classify/pdist2.m
| 5,162 |
utf_8
|
768ff9e8818251f756c8325368ee7d90
|
function D = pdist2( X, Y, metric )
% Calculates the distance between sets of vectors.
%
% Let X be an m-by-p matrix representing m points in p-dimensional space
% and Y be an n-by-p matrix representing another set of points in the same
% space. This function computes the m-by-n distance matrix D where D(i,j)
% is the distance between X(i,:) and Y(j,:). This function has been
% optimized where possible, with most of the distance computations
% requiring few or no loops.
%
% The metric can be one of the following:
%
% 'euclidean' / 'sqeuclidean':
% Euclidean / SQUARED Euclidean distance. Note that 'sqeuclidean'
% is significantly faster.
%
% 'chisq'
% The chi-squared distance between two vectors is defined as:
% d(x,y) = sum( (xi-yi)^2 / (xi+yi) ) / 2;
% The chi-squared distance is useful when comparing histograms.
%
% 'cosine'
% Distance is defined as the cosine of the angle between two vectors.
%
% 'emd'
% Earth Mover's Distance (EMD) between positive vectors (histograms).
% Note for 1D, with all histograms having equal weight, there is a simple
% closed form for the calculation of the EMD. The EMD between histograms
% x and y is given by the sum(abs(cdf(x)-cdf(y))), where cdf is the
% cumulative distribution function (computed simply by cumsum).
%
% 'L1'
% The L1 distance between two vectors is defined as: sum(abs(x-y));
%
%
% USAGE
% D = pdist2( X, Y, [metric] )
%
% INPUTS
% X - [m x p] matrix of m p-dimensional vectors
% Y - [n x p] matrix of n p-dimensional vectors
% metric - ['sqeuclidean'], 'chisq', 'cosine', 'emd', 'euclidean', 'L1'
%
% OUTPUTS
% D - [m x n] distance matrix
%
% EXAMPLE
% % simple example where points cluster well
% [X,IDX] = demoGenData(100,0,5,4,10,2,0);
% D = pdist2( X, X, 'sqeuclidean' );
% distMatrixShow( D, IDX );
% % comparison to pdist
% n=500; d=200; r=100; X=rand(n,d);
% tic, for i=1:r, D1 = pdist( X, 'euclidean' ); end, toc
% tic, for i=1:r, D2 = pdist2( X, X, 'euclidean' ); end, toc
% D1=squareform(D1); del=D1-D2; sum(abs(del(:)))
%
% See also pdist, distMatrixShow
%
% Piotr's Computer Vision Matlab Toolbox Version 2.52
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<3 || isempty(metric) ); metric=0; end;
switch metric
case {0,'sqeuclidean'}
D = distEucSq( X, Y );
case 'euclidean'
D = sqrt(distEucSq( X, Y ));
case 'L1'
D = distL1( X, Y );
case 'cosine'
D = distCosine( X, Y );
case 'emd'
D = distEmd( X, Y );
case 'chisq'
D = distChiSq( X, Y );
otherwise
error(['pdist2 - unknown metric: ' metric]);
end
D = max(0,D);
end
function D = distL1( X, Y )
m = size(X,1); n = size(Y,1);
mOnes = ones(1,m); D = zeros(m,n);
for i=1:n
yi = Y(i,:); yi = yi( mOnes, : );
D(:,i) = sum( abs( X-yi),2 );
end
end
function D = distCosine( X, Y )
p=size(X,2);
XX = sqrt(sum(X.*X,2)); X = X ./ XX(:,ones(1,p));
YY = sqrt(sum(Y.*Y,2)); Y = Y ./ YY(:,ones(1,p));
D = 1 - X*Y';
end
function D = distEmd( X, Y )
Xcdf = cumsum(X,2);
Ycdf = cumsum(Y,2);
m = size(X,1); n = size(Y,1);
mOnes = ones(1,m); D = zeros(m,n);
for i=1:n
ycdf = Ycdf(i,:);
ycdfRep = ycdf( mOnes, : );
D(:,i) = sum(abs(Xcdf - ycdfRep),2);
end
end
function D = distChiSq( X, Y )
% note: supposedly it's possible to implement this without a loop!
m = size(X,1); n = size(Y,1);
mOnes = ones(1,m); D = zeros(m,n);
for i=1:n
yi = Y(i,:); yiRep = yi( mOnes, : );
s = yiRep + X; d = yiRep - X;
D(:,i) = sum( d.^2 ./ (s+eps), 2 );
end
D = D/2;
end
function D = distEucSq( X, Y )
Yt = Y';
XX = sum(X.*X,2);
YY = sum(Yt.*Yt,1);
D = bsxfun(@plus,XX,YY)-2*X*Yt;
end
%%%% code from Charles Elkan with variables renamed
% function D = distEucSq( X, Y )
% m = size(X,1); n = size(Y,1);
% D = sum(X.^2, 2) * ones(1,n) + ones(m,1) * sum(Y.^2, 2)' - 2.*X*Y';
% end
%%% LOOP METHOD - SLOW
% [m p] = size(X);
% [n p] = size(Y);
% D = zeros(m,n);
% onesM = ones(m,1);
% for i=1:n
% y = Y(i,:);
% d = X - y(onesM,:);
% D(:,i) = sum( d.*d, 2 );
% end
%%% PARALLEL METHOD THAT IS SUPER SLOW (slower than loop)!
% % From "MATLAB array manipulation tips and tricks" by Peter J. Acklam
% Xb = permute(X, [1 3 2]);
% Yb = permute(Y, [3 1 2]);
% D = sum( (Xb(:,ones(1,n),:) - Yb(ones(1,m),:,:)).^2, 3);
%%% USELESS FOR EVEN VERY LARGE ARRAYS X=16000x1000!! and Y=100x1000
% call recursively to save memory
% if( (m+n)*p > 10^5 && (m>1 || n>1))
% if( m>n )
% X1 = X(1:floor(end/2),:);
% X2 = X((floor(end/2)+1):end,:);
% D1 = distEucSq( X1, Y );
% D2 = distEucSq( X2, Y );
% D = cat( 1, D1, D2 );
% else
% Y1 = Y(1:floor(end/2),:);
% Y2 = Y((floor(end/2)+1):end,:);
% D1 = distEucSq( X, Y1 );
% D2 = distEucSq( X, Y2 );
% D = cat( 2, D1, D2 );
% end
% return;
% end
%%% L1 COMPUTATION WITH LOOP OVER p, FAST FOR SMALL p.
% function D = distL1( X, Y )
%
% m = size(X,1); n = size(Y,1); p = size(X,2);
% mOnes = ones(1,m); nOnes = ones(1,n); D = zeros(m,n);
% for i=1:p
% yi = Y(:,i); yi = yi( :, mOnes );
% xi = X(:,i); xi = xi( :, nOnes );
% D = D + abs( xi-yi' );
% end
|
github
|
3arbouch/PersonDetection-master
|
pca.m
|
.m
|
PersonDetection-master/Source/toolbox/classify/pca.m
| 3,244 |
utf_8
|
848f2eb05c18a6e448e9d22af27b9422
|
function [U,mu,vars] = pca( X )
% Principal components analysis (alternative to princomp).
%
% A simple linear dimensionality reduction technique. Use to create an
% orthonormal basis for the points in R^d such that the coordinates of a
% vector x in this basis are of decreasing importance. Instead of using all
% d basis vectors to specify the location of x, using only the first k<d
% still gives a vector xhat that is close to x.
%
% This function operates on arrays of arbitrary dimension, by first
% converting the arrays to vectors. If X is m+1 dimensional, say of size
% [d1 x d2 x...x dm x n], then the first m dimensions of X are combined. X
% is flattened to be 2 dimensional: [dxn], with d=prod(di). Once X is
% converted to 2 dimensions of size dxn, each column represents a single
% observation, and each row is a different variable. Note that this is the
% opposite of many matlab functions such as princomp. If X is MxNxn, then
% X(:,:,i) represents the ith observation (useful for stack of n images),
% likewise for n videos X is MxNxKxn. If X is very large, it is sampled
% before running PCA. Use this function to retrieve the basis U. Use
% pcaApply to retrieve that basis coefficients for a novel vector x. Use
% pcaVisualize(X,...) for visualization of approximated X.
%
% To calculate residuals:
% residuals = cumsum(vars/sum(vars)); plot(residuals,'-.')
%
% USAGE
% [U,mu,vars] = pca( X )
%
% INPUTS
% X - [d1 x ... x dm x n], treated as n [d1 x ... x dm] elements
%
% OUTPUTS
% U - [d x r], d=prod(di), each column is a principal component
% mu - [d1 x ... x dm] mean of X
% vars - sorted eigenvalues corresponding to eigenvectors in U
%
% EXAMPLE
% load pcaData;
% [U,mu,vars] = pca( I3D1(:,:,1:12) );
% [Y,Xhat,avsq] = pcaApply( I3D1(:,:,1), U, mu, 5 );
% pcaVisualize( U, mu, vars, I3D1, 13, [0:12], [], 1 );
% Xr = pcaRandVec( U, mu, vars, 1, 25, 0, 3 );
%
% See also princomp, pcaApply, pcaVisualize, pcaRandVec, visualizeData
%
% Piotr's Computer Vision Matlab Toolbox Version 3.24
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% set X to be zero mean, then flatten
d=size(X); n=d(end); d=prod(d(1:end-1));
if(~isa(X,'double')), X=double(X); end
if(n==1); mu=X; U=zeros(d,1); vars=0; return; end
mu = mean( X, ndims(X) );
X = bsxfun(@minus,X,mu)/sqrt(n-1);
X = reshape( X, d, n );
% make sure X not too large or SVD slow O(min(d,n)^2.5)
m=2500; if( min(d,n)>m ), X=X(:,randperm(n,m)); n=m; end
% get principal components using the SVD of X: X=U*S*V'
if( 0 )
[U,S]=svd(X,'econ'); vars=diag(S).^2;
elseif( d>n )
[~,SS,V]=robustSvd(X'*X); vars=diag(SS);
U = X * V * diag(1./sqrt(vars));
else
[~,SS,U]=robustSvd(X*X'); vars=diag(SS);
end
% discard low variance prinicipal components
K=vars>1e-30; vars=vars(K); U=U(:,K);
end
function [U,S,V] = robustSvd( X, trials )
% Robust version of SVD more likely to always converge.
% [Converge issues only seem to appear on Matlab 2013a in Windows.]
if(nargin<2), trials=100; end
try [U,S,V] = svd(X); catch
if(trials<=0), error('svd did not converge'); end
n=numel(X); j=randi(n); X(j)=X(j)+eps;
[U,S,V]=robustSvd(X,trials-1);
end
end
|
github
|
3arbouch/PersonDetection-master
|
kmeans2.m
|
.m
|
PersonDetection-master/Source/toolbox/classify/kmeans2.m
| 5,251 |
utf_8
|
f941053f03c3e9eda40389a4cc64ee00
|
function [ IDX, C, d ] = kmeans2( X, k, varargin )
% Fast version of kmeans clustering.
%
% Cluster the N x p matrix X into k clusters using the kmeans algorithm. It
% returns the cluster memberships for each data point in the N x 1 vector
% IDX and the K x p matrix of cluster means in C.
%
% This function is in some ways less general than Matlab's kmeans.m (for
% example it only uses euclidian distance), but it has some options that
% the Matlab version does not (for example, it has a notion of outliers and
% min-cluster size). It is also many times faster than matlab's kmeans.
% General kmeans help can be found in help for the matlab implementation of
% kmeans. Note that the although the names and conventions for this
% algorithm are taken from Matlab's implementation, there are slight
% alterations (for example, IDX==-1 is used to indicate outliers).
%
% IDX is a n-by-1 vector used to indicated cluster membership. Let X be a
% set of n points. Then the ID of X - or IDX is a column vector of length
% n, where each element is an integer indicating the cluster membership of
% the corresponding element in X. IDX(i)=c indicates that the ith point in
% X belongs to cluster c. Cluster labels range from 1 to k, and thus
% k=max(IDX) is typically the number of clusters IDX divides X into. The
% cluster label "-1" is reserved for outliers. IDX(i)==-1 indicates that
% the given point does not belong to any of the discovered clusters. Note
% that matlab's version of kmeans does not have outliers.
%
% USAGE
% [ IDX, C, d ] = kmeans2( X, k, [varargin] )
%
% INPUTS
% X - [n x p] matrix of n p-dim vectors.
% k - maximum nuber of clusters (actual number may be smaller)
% prm - additional params (struct or name/value pairs)
% .k - [] alternate way of specifying k (if not given above)
% .nTrial - [1] number random restarts
% .maxIter - [100] max number of iterations
% .display - [0] Whether or not to display algorithm status
% .rndSeed - [] random seed for kmeans; useful for replicability
% .outFrac - [0] max frac points that can be treated as outliers
% .minCl - [1] min cluster size (smaller clusters get eliminated)
% .metric - [] metric for pdist2
% .C0 - [] initial cluster centers for first trial
%
% OUTPUTS
% IDX - [n x 1] cluster membership (see above)
% C - [k x p] matrix of centroid locations C(j,:) = mean(X(IDX==j,:))
% d - [1 x k] d(j) is sum of distances from X(IDX==j,:) to C(j,:)
% sum(d) is a typical measure of the quality of a clustering
%
% EXAMPLE
%
% See also DEMOCLUSTER
%
% Piotr's Computer Vision Matlab Toolbox Version 3.24
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get input args
dfs = {'nTrial',1, 'maxIter',100, 'display',0, 'rndSeed',[],...
'outFrac',0, 'minCl',1, 'metric',[], 'C0',[],'k',k };
[nTrial,maxt,dsp,rndSeed,outFrac,minCl,metric,C0,k] = ...
getPrmDflt(varargin,dfs); assert(~isempty(k) && k>0);
% error checking
if(k<1); error('k must be greater than 1'); end
if(~ismatrix(X) || any(size(X)==0)); error('Illegal X'); end
if(outFrac<0 || outFrac>=1), error('outFrac must be in [0,1)'); end
nOut = floor( size(X,1)*outFrac );
% initialize random seed if specified
if(~isempty(rndSeed)); rand('state',rndSeed); end; %#ok<RAND>
% run kmeans2main nTrial times
bd=inf; t0=clock;
for i=1:nTrial, t1=clock; if(i>1), C0=[]; end
if(dsp), fprintf('kmeans2 iter %i/%i step: ',i,nTrial); end
[IDX,C,d]=kmeans2main(X,k,nOut,minCl,maxt,dsp,metric,C0);
if(sum(d)<sum(bd)), bIDX=IDX; bC=C; bd=d; end
if(dsp), fprintf(' d=%f t=%fs\n',sum(d),etime(clock,t1)); end
end
IDX=bIDX; C=bC; d=bd; k=max(IDX);
if(dsp), fprintf('k=%i d=%f t=%fs\n',k,sum(d),etime(clock,t0)); end
% sort IDX to have biggest clusters have lower indicies
cnts = zeros(1,k); for i=1:k; cnts(i) = sum( IDX==i ); end
[~,order] = sort( -cnts ); C = C(order,:); d = d(order);
IDX2=IDX; for i=1:k; IDX2(IDX==order(i))=i; end; IDX = IDX2;
end
function [IDX,C,d] = kmeans2main( X, k, nOut, minCl, maxt, dsp, metric, C )
% initialize cluster centers to be k random X points
[N,p] = size(X); k = min(k,N); t=0;
IDX = ones(N,1); oldIDX = zeros(N,1);
if(isempty(C)), C = X(randperm(N,k),:)+randn(k,p)/1e5; end
% MAIN LOOP: loop until the cluster assigments do not change
if(dsp), nDg=ceil(log10(maxt-1)); fprintf(int2str2(0,nDg)); end
while( any(oldIDX~=IDX) && t<maxt )
% assign each point to closest cluster center
oldIDX=IDX; D=pdist2(X,C,metric); [mind,IDX]=min(D,[],2);
% do not use most distant nOut elements in computation of centers
mind1=sort(mind); thr=mind1(end-nOut); IDX(mind>thr)=-1;
% Recalculate means based on new assignment, discard small clusters
k0=0; C=zeros(k,p);
for IDx=1:k
ids=find(IDX==IDx); nCl=size(ids,1);
if( nCl<minCl ), IDX(ids)=-1; continue; end
k0=k0+1; IDX(ids)=k0; C(k0,:)=sum(X(ids,:),1)/nCl;
end
if(k0>0), k=k0; C=C(1:k,:); else k=1; C=X(randint2(1,1,[1 N]),:); end
t=t+1; if(dsp), fprintf([repmat('\b',[1 nDg]) int2str2(t,nDg)]); end
end
% record within-cluster sums of point-to-centroid distances
d=zeros(1,k); for i=1:k, d(i)=sum(mind(IDX==i)); end
end
|
github
|
3arbouch/PersonDetection-master
|
acfModify.m
|
.m
|
PersonDetection-master/Source/toolbox/detector/acfModify.m
| 4,202 |
utf_8
|
7a49406d51e7a9431b8fd472be0476e8
|
function detector = acfModify( detector, varargin )
% Modify aggregate channel features object detector.
%
% Takes an object detector trained by acfTrain() and modifies it. Only
% certain modifications are allowed to the detector and the detector should
% never be modified directly (this may cause the detector to be invalid and
% cause segmentation faults). Any valid modification to a detector after it
% is trained should be performed using acfModify().
%
% The parameters 'nPerOct', 'nOctUp', 'nApprox', 'lambdas', 'pad', 'minDs'
% modify the channel feature pyramid created (see help of chnsPyramid.m for
% more details) and primarily control the scales used. The parameters
% 'pNms', 'stride', 'cascThr' and 'cascCal' modify the detector behavior
% (see help of acfTrain.m for more details). Finally, 'rescale' can be
% used to rescale the trained detector (this change is irreversible).
%
% USAGE
% detector = acfModify( detector, pModify )
%
% INPUTS
% detector - detector trained via acfTrain
% pModify - parameters (struct or name/value pairs)
% .nPerOct - [] number of scales per octave
% .nOctUp - [] number of upsampled octaves to compute
% .nApprox - [] number of approx. scales to use
% .lambdas - [] coefficients for power law scaling (see BMVC10)
% .pad - [] amount to pad channels (along T/B and L/R)
% .minDs - [] minimum image size for channel computation
% .pNms - [] params for non-maximal suppression (see bbNms.m)
% .stride - [] spatial stride between detection windows
% .cascThr - [] constant cascade threshold (affects speed/accuracy)
% .cascCal - [] cascade calibration (affects speed/accuracy)
% .rescale - [] rescale entire detector by given ratio
%
% OUTPUTS
% detector - modified object detector
%
% EXAMPLE
%
% See also chnsPyramid, bbNms, acfTrain, acfDetect
%
% Piotr's Computer Vision Matlab Toolbox Version 3.20
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get parameters (and copy to detector and pPyramid structs)
opts=detector.opts; p=opts.pPyramid;
dfs={ 'nPerOct',p.nPerOct, 'nOctUp',p.nOctUp, 'nApprox',p.nApprox, ...
'lambdas',p.lambdas, 'pad',p.pad, 'minDs',p.minDs, 'pNms',opts.pNms, ...
'stride',opts.stride,'cascThr',opts.cascThr,'cascCal',0,'rescale',1 };
[p.nPerOct,p.nOctUp,p.nApprox,p.lambdas,p.pad,p.minDs,opts.pNms,...
opts.stride,opts.cascThr,cascCal,rescale] = getPrmDflt(varargin,dfs,1);
% finalize pPyramid and opts
p.complete=0; p.pChns.complete=0; p=chnsPyramid([],p); p=p.pPyramid;
p.complete=1; p.pChns.complete=1; shrink=p.pChns.shrink;
opts.stride=max(1,round(opts.stride/shrink))*shrink;
opts.pPyramid=p; detector.opts=opts;
% calibrate and rescale detector
detector.clf.hs = detector.clf.hs+cascCal;
if(rescale~=1), detector=detectorRescale(detector,rescale); end
end
function detector = detectorRescale( detector, rescale )
% Rescale detector by ratio rescale.
opts=detector.opts; shrink=opts.pPyramid.pChns.shrink;
bh=opts.modelDsPad(1)/shrink; bw=opts.modelDsPad(2)/shrink;
opts.stride=max(1,round(opts.stride*rescale/shrink))*shrink;
modelDsPad=round(opts.modelDsPad*rescale/shrink)*shrink;
rescale=modelDsPad./opts.modelDsPad; opts.modelDsPad=modelDsPad;
opts.modelDs=round(opts.modelDs.*rescale); detector.opts=opts;
bh1=opts.modelDsPad(1)/shrink; bw1=opts.modelDsPad(2)/shrink;
% move 0-indexed (x,y) location of each lookup feature
clf=detector.clf; fids=clf.fids; is=find(clf.child>0);
fids=double(fids(is)); n=length(fids); loc=zeros(n,3);
loc(:,3)=floor(fids/bh/bw); fids=fids-loc(:,3)*bh*bw;
loc(:,2)=floor(fids/bh); fids=fids-loc(:,2)*bh; loc(:,1)=fids;
loc(:,1)=min(bh1-1,round(loc(:,1)*rescale(1)));
loc(:,2)=min(bw1-1,round(loc(:,2)*rescale(2)));
fids = loc(:,3)*bh1*bw1 + loc(:,2)*bh1 + loc(:,1);
clf.fids(is)=int32(fids);
% rescale thrs for all features (fpdw trick)
nChns=[detector.info.nChns]; assert(max(loc(:,3))<sum(nChns));
k=[]; for i=1:length(nChns), k=[k ones(1,nChns(i))*i]; end %#ok<AGROW>
lambdas=opts.pPyramid.lambdas; lambdas=sqrt(prod(rescale)).^-lambdas(k);
clf.thrs(is)=clf.thrs(is).*lambdas(loc(:,3)+1)'; detector.clf=clf;
end
|
github
|
3arbouch/PersonDetection-master
|
acfDetect.m
|
.m
|
PersonDetection-master/Source/toolbox/detector/acfDetect.m
| 3,659 |
utf_8
|
cf1384311b16371be6fa4715140e5c81
|
function bbs = acfDetect( I, detector, fileName )
% Run aggregate channel features object detector on given image(s).
%
% The input 'I' can either be a single image (or filename) or a cell array
% of images (or filenames). In the first case, the return is a set of bbs
% where each row has the format [x y w h score] and score is the confidence
% of detection. If the input is a cell array, the output is a cell array
% where each element is a set of bbs in the form above (in this case a
% parfor loop is used to speed execution). If 'fileName' is specified, the
% bbs are saved to a comma separated text file and the output is set to
% bbs=1. If saving detections for multiple images the output is stored in
% the format [imgId x y w h score] and imgId is a one-indexed image id.
%
% A cell of detectors trained with the same channels can be specified,
% detected bbs from each detector are concatenated. If using multiple
% detectors and opts.pNms.separate=1 then each bb has a sixth element
% bbType=j, where j is the j-th detector, see bbNms.m for details.
%
% USAGE
% bbs = acfDetect( I, detector, [fileName] )
%
% INPUTS
% I - input image(s) of filename(s) of input image(s)
% detector - detector(s) trained via acfTrain
% fileName - [] target filename (if specified return is 1)
%
% OUTPUTS
% bbs - [nx5] array of bounding boxes or cell array of bbs
%
% EXAMPLE
%
% See also acfTrain, acfModify, bbGt>loadAll, bbNms
%
% Piotr's Computer Vision Matlab Toolbox Version 3.40
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% run detector on every image
if(nargin<3), fileName=''; end; multiple=iscell(I);
if(~isempty(fileName) && exist(fileName,'file')), bbs=1; return; end
if(~multiple), bbs=acfDetectImg(I,detector); else
n=length(I); bbs=cell(n,1);
parfor i=1:n, bbs{i}=acfDetectImg(I{i},detector); end
end
% write results to disk if fileName specified
if(isempty(fileName)), return; end
d=fileparts(fileName); if(~isempty(d)&&~exist(d,'dir')), mkdir(d); end
if( multiple ) % add image index to each bb and flatten result
for i=1:n, bbs{i}=[ones(size(bbs{i},1),1)*i bbs{i}]; end
bbs=cell2mat(bbs);
end
dlmwrite(fileName,bbs); bbs=1;
end
function bbs = acfDetectImg( I, detector )
% Run trained sliding-window object detector on given image.
Ds=detector; if(~iscell(Ds)), Ds={Ds}; end; nDs=length(Ds);
opts=Ds{1}.opts; pPyramid=opts.pPyramid; pNms=opts.pNms;
imreadf=opts.imreadf; imreadp=opts.imreadp;
shrink=pPyramid.pChns.shrink; pad=pPyramid.pad;
separate=nDs>1 && isfield(pNms,'separate') && pNms.separate;
% read image and compute features (including optionally applying filters)
if(all(ischar(I))), I=feval(imreadf,I,imreadp{:}); end
P=chnsPyramid(I,pPyramid); bbs=cell(P.nScales,nDs);
if(isfield(opts,'filters') && ~isempty(opts.filters)), shrink=shrink*2;
for i=1:P.nScales, fs=opts.filters; C=repmat(P.data{i},[1 1 size(fs,4)]);
for j=1:size(C,3), C(:,:,j)=conv2(C(:,:,j),fs(:,:,j),'same'); end
P.data{i}=imResample(C,.5);
end
end
% apply sliding window classifiers
for i=1:P.nScales
for j=1:nDs, opts=Ds{j}.opts;
modelDsPad=opts.modelDsPad; modelDs=opts.modelDs;
bb = acfDetect1(P.data{i},Ds{j}.clf,shrink,...
modelDsPad(1),modelDsPad(2),opts.stride,opts.cascThr);
shift=(modelDsPad-modelDs)/2-pad;
bb(:,1)=(bb(:,1)+shift(2))/P.scaleshw(i,2);
bb(:,2)=(bb(:,2)+shift(1))/P.scaleshw(i,1);
bb(:,3)=modelDs(2)/P.scales(i);
bb(:,4)=modelDs(1)/P.scales(i);
if(separate), bb(:,6)=j; end; bbs{i,j}=bb;
end
end; bbs=cat(1,bbs{:});
if(~isempty(pNms)), bbs=bbNms(bbs,pNms); end
end
|
github
|
3arbouch/PersonDetection-master
|
bbGt.m
|
.m
|
PersonDetection-master/Source/toolbox/detector/bbGt.m
| 34,046 |
utf_8
|
69e66c9a0cc143fb9a794fbc9233246e
|
function varargout = bbGt( action, varargin )
% Bounding box (bb) annotations struct, evaluation and sampling routines.
%
% bbGt gives access to two types of routines:
% (1) Data structure for storing bb image annotations.
% (2) Routines for evaluating the Pascal criteria for object detection.
%
% The bb annotation stores bb for objects of interest with additional
% information per object, such as occlusion information. The underlying
% data structure is simply a Matlab stuct array, one struct per object.
% This annotation format is an alternative to the annotation format used
% for the PASCAL object challenges (in addition routines for loading PASCAL
% format data are provided, see bbLoad()).
%
% Each object struct has the following fields:
% lbl - a string label describing object type (eg: 'pedestrian')
% bb - [l t w h]: bb indicating predicted object extent
% occ - 0/1 value indicating if bb is occluded
% bbv - [l t w h]: bb indicating visible region (may be [0 0 0 0])
% ign - 0/1 value indicating bb was marked as ignore
% ang - [0-360] orientation of bb in degrees
%
% Note: although orientation (angle) is stored for each bb, for now it is
% not being used during evaluation or sampling.
%
% bbGt contains a number of utility functions, accessed using:
% outputs = bbGt( 'action', inputs );
% The list of functions and help for each is given below. Also, help on
% individual subfunctions can be accessed by: "help bbGt>action".
%
%%% (1) Data structure for storing bb image annotations.
% Create annotation of n empty objects.
% objs = bbGt( 'create', [n] );
% Save bb annotation to text file.
% objs = bbGt( 'bbSave', objs, fName )
% Load bb annotation from text file and filter.
% [objs,bbs] = bbGt( 'bbLoad', fName, [pLoad] )
% Get object property 'name' (in a standard array).
% vals = bbGt( 'get', objs, name )
% Set object property 'name' (with a standard array).
% objs = bbGt( 'set', objs, name, vals )
% Draw an ellipse for each labeled object.
% hs = draw( objs, pDraw )
%
%%% (2) Routines for evaluating the Pascal criteria for object detection.
% Get all corresponding files in given directories.
% [fs,fs0] = bbGt('getFiles', dirs, [f0], [f1] )
% Copy corresponding files into given directories.
% fs = bbGt( 'copyFiles', fs, dirs )
% Load all ground truth and detection bbs in given directories.
% [gt0,dt0] = bbGt( 'loadAll', gtDir, [dtDir], [pLoad] )
% Evaluates detections against ground truth data.
% [gt,dt] = bbGt( 'evalRes', gt0, dt0, [thr], [mul] )
% Display evaluation results for given image.
% [hs,hImg] = bbGt( 'showRes' I, gt, dt, varargin )
% Compute ROC or PR based on outputs of evalRes on multiple images.
% [xs,ys,ref] = bbGt( 'compRoc', gt, dt, roc, ref )
% Extract true or false positives or negatives for visualization.
% [Is,scores,imgIds] = bbGt( 'cropRes', gt, dt, imFs, varargin )
% Computes (modified) overlap area between pairs of bbs.
% oa = bbGt( 'compOas', dt, gt, [ig] )
% Optimized version of compOas for a single pair of bbs.
% oa = bbGt( 'compOa', dt, gt, ig )
%
% USAGE
% varargout = bbGt( action, varargin );
%
% INPUTS
% action - string specifying action
% varargin - depends on action, see above
%
% OUTPUTS
% varargout - depends on action, see above
%
% EXAMPLE
%
% See also bbApply, bbLabeler, bbGt>create, bbGt>bbSave, bbGt>bbLoad,
% bbGt>get, bbGt>set, bbGt>draw, bbGt>getFiles, bbGt>copyFiles,
% bbGt>loadAll, bbGt>evalRes, bbGt>showRes, bbGt>compRoc, bbGt>cropRes,
% bbGt>compOas, bbGt>compOa
%
% Piotr's Computer Vision Matlab Toolbox Version 3.26
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%#ok<*DEFNU>
varargout = cell(1,max(1,nargout));
[varargout{:}] = feval(action,varargin{:});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function objs = create( n )
% Create annotation of n empty objects.
%
% USAGE
% objs = bbGt( 'create', [n] )
%
% INPUTS
% n - [1] number of objects to create
%
% OUTPUTS
% objs - annotation of n 'empty' objects
%
% EXAMPLE
% objs = bbGt('create')
%
% See also bbGt
o=struct('lbl','','bb',[0 0 0 0],'occ',0,'bbv',[0 0 0 0],'ign',0,'ang',0);
if(nargin<1 || n==1), objs=o; return; end; objs=o(ones(n,1));
end
function objs = bbSave( objs, fName )
% Save bb annotation to text file.
%
% USAGE
% objs = bbGt( 'bbSave', objs, fName )
%
% INPUTS
% objs - objects to save
% fName - name of text file
%
% OUTPUTS
% objs - objects to save
%
% EXAMPLE
%
% See also bbGt, bbGt>bbLoad
vers=3; fid=fopen(fName,'w'); assert(fid>0);
fprintf(fid,'%% bbGt version=%i\n',vers);
objs=set(objs,'bb',round(get(objs,'bb')));
objs=set(objs,'bbv',round(get(objs,'bbv')));
objs=set(objs,'ang',round(get(objs,'ang')));
for i=1:length(objs)
o=objs(i); bb=o.bb; bbv=o.bbv;
fprintf(fid,['%s' repmat(' %i',1,11) '\n'],o.lbl,...
bb,o.occ,bbv,o.ign,o.ang);
end
fclose(fid);
end
function [objs,bbs] = bbLoad( fName, varargin )
% Load bb annotation from text file and filter.
%
% FORMAT: Specify 'format' to indicate the format of the ground truth.
% format=0 is the default format (created by bbSave/bbLabeler). format=1 is
% the PASCAL VOC format. Loading ground truth in this format requires
% 'VOCcode/' to be in directory path. It's part of VOCdevkit available from
% the PASCAL VOC: http://pascallin.ecs.soton.ac.uk/challenges/VOC/. Objects
% labeled as either 'truncated' or 'occluded' using the PASCAL definitions
% have the 'occ' flag set to true. Objects labeled as 'difficult' have the
% 'ign' flag set to true. 'class' is used for 'lbl'. format=2 is the
% ImageNet detection format and requires the ImageNet Dev Kit.
%
% FILTERING: After loading, the objects can be filtered. First, only
% objects with lbl in lbls or ilbls or returned. For each object, obj.ign
% is set to 1 if it was already at 1, if its label was in ilbls, or if any
% object property is outside of the specified range. The ignore flag is
% used during training and testing so that objects with certain properties
% (such as very small or heavily occluded objects) are excluded. The range
% for each property is a two element vector, [0 inf] by default; a property
% value v is inside the range if v>=rng(1) && v<=rng(2). Tested properties
% include height (h), width (w), area (a), aspect ratio (ar), orientation
% (o), extent x-coordinate (x), extent y-coordinate (y), and fraction
% visible (v). The last property is computed as the visible object area
% divided by the total area, except if o.occ==0, in which case v=1, or
% all(o.bbv==o.bb), which indicates the object may be barely visible, in
% which case v=0 (note that v~=1 in this case).
%
% RETURN: In addition to outputting the objs, bbLoad() can return the
% corresponding bounding boxes (bbs) in an [nx5] array where each row is of
% the form [x y w h ignore], [x y w h] is the bb and ignore=obj.ign. For
% oriented bbs, the extent of the bb is returned, where the extent is the
% smallest axis aligned bb containing the oriented bb. If the oriented bb
% was labeled as a rectangle as opposed to an ellipse, the tightest bb will
% usually increase slightly in size due to the corners of the rectangle
% sticking out beyond the ellipse bounds. The 'ellipse' flag controls how
% an oriented bb is converted to a regular bb. Specifically, set ellipse=1
% if an ellipse tightly delineates the object and 0 if a rectangle does.
% Finally, if 'squarify' is not empty the (non-ignore) bbs are converted to
% a fixed aspect ratio using bbs=bbApply('squarify',bbs,squarify{:}).
%
% USAGE
% [objs,bbs] = bbGt( 'bbLoad', fName, [pLoad] )
%
% INPUTS
% fName - name of text file
% pLoad - parameters (struct or name/value pairs)
% .format - [0] gt format 0:default, 1:PASCAL, 2:ImageNet
% .ellipse - [1] controls how oriented bb is converted to regular bb
% .squarify - [] controls optional reshaping of bbs to fixed aspect ratio
% .lbls - [] return objs with these labels (or [] to return all)
% .ilbls - [] return objs with these labels but set to ignore
% .hRng - [] range of acceptable obj heights
% .wRng - [] range of acceptable obj widths
% .aRng - [] range of acceptable obj areas
% .arRng - [] range of acceptable obj aspect ratios
% .oRng - [] range of acceptable obj orientations (angles)
% .xRng - [] range of x coordinates of bb extent
% .yRng - [] range of y coordinates of bb extent
% .vRng - [] range of acceptable obj occlusion levels
%
% OUTPUTS
% objs - loaded objects
% bbs - [nx5] array containg ground truth bbs [x y w h ignore]
%
% EXAMPLE
%
% See also bbGt, bbGt>bbSave
% get parameters
df={'format',0,'ellipse',1,'squarify',[],'lbls',[],'ilbls',[],'hRng',[],...
'wRng',[],'aRng',[],'arRng',[],'oRng',[],'xRng',[],'yRng',[],'vRng',[]};
[format,ellipse,sqr,lbls,ilbls,hRng,wRng,aRng,arRng,oRng,xRng,yRng,vRng]...
= getPrmDflt(varargin,df,1);
% load objs
if( format==0 )
% load objs stored in default format
fId=fopen(fName);
if(fId==-1), error(['unable to open file: ' fName]); end; v=0;
try v=textscan(fId,'%% bbGt version=%d'); v=v{1}; catch, end %#ok<CTCH>
if(isempty(v)), v=0; end
% read in annotation (m is number of fields for given version v)
if(all(v~=[0 1 2 3])), error('Unknown version %i.',v); end
frmt='%s %d %d %d %d %d %d %d %d %d %d %d';
ms=[10 10 11 12]; m=ms(v+1); frmt=frmt(1:2+(m-1)*3);
in=textscan(fId,frmt); for i=2:m, in{i}=double(in{i}); end; fclose(fId);
% create objs struct from read in fields
n=length(in{1}); objs=create(n);
for i=1:n, objs(i).lbl=in{1}{i}; objs(i).occ=in{6}(i); end
bb=[in{2} in{3} in{4} in{5}]; bbv=[in{7} in{8} in{9} in{10}];
for i=1:n, objs(i).bb=bb(i,:); objs(i).bbv=bbv(i,:); end
if(m>=11), for i=1:n, objs(i).ign=in{11}(i); end; end
if(m>=12), for i=1:n, objs(i).ang=in{12}(i); end; end
elseif( format==1 )
% load objs stored in PASCAL VOC format
if(exist('PASreadrecord.m','file')~=2)
error('bbLoad() requires the PASCAL VOC code.'); end
os=PASreadrecord(fName); os=os.objects;
n=length(os); objs=create(n);
if(~isfield(os,'occluded')), for i=1:n, os(i).occluded=0; end; end
for i=1:n
bb=os(i).bbox; bb(3)=bb(3)-bb(1); bb(4)=bb(4)-bb(2); objs(i).bb=bb;
objs(i).lbl=os(i).class; objs(i).ign=os(i).difficult;
objs(i).occ=os(i).occluded || os(i).truncated;
if(objs(i).occ), objs(i).bbv=bb; end
end
elseif( format==2 )
if(exist('VOCreadxml.m','file')~=2)
error('bbLoad() requires the ImageNet dev code.'); end
os=VOCreadxml(fName); os=os.annotation;
if(isfield(os,'object')), os=os.object; else os=[]; end
n=length(os); objs=create(n);
for i=1:n
bb=os(i).bndbox; bb=str2double({bb.xmin bb.ymin bb.xmax bb.ymax});
bb(3)=bb(3)-bb(1); bb(4)=bb(4)-bb(2); objs(i).bb=bb;
objs(i).lbl=os(i).name;
end
else error('bbLoad() unknown format: %i',format);
end
% only keep objects whose lbl is in lbls or ilbls
if(~isempty(lbls) || ~isempty(ilbls)), K=true(n,1);
for i=1:n, K(i)=any(strcmp(objs(i).lbl,[lbls ilbls])); end
objs=objs(K); n=length(objs);
end
% filter objs (set ignore flags)
for i=1:n, objs(i).ang=mod(objs(i).ang,360); end
if(~isempty(ilbls)), for i=1:n, v=objs(i).lbl;
objs(i).ign = objs(i).ign || any(strcmp(v,ilbls)); end; end
if(~isempty(xRng)), for i=1:n, v=objs(i).bb(1);
objs(i).ign = objs(i).ign || v<xRng(1) || v>xRng(2); end; end
if(~isempty(xRng)), for i=1:n, v=objs(i).bb(1)+objs(i).bb(3);
objs(i).ign = objs(i).ign || v<xRng(1) || v>xRng(2); end; end
if(~isempty(yRng)), for i=1:n, v=objs(i).bb(2);
objs(i).ign = objs(i).ign || v<yRng(1) || v>yRng(2); end; end
if(~isempty(yRng)), for i=1:n, v=objs(i).bb(2)+objs(i).bb(4);
objs(i).ign = objs(i).ign || v<yRng(1) || v>yRng(2); end; end
if(~isempty(wRng)), for i=1:n, v=objs(i).bb(3);
objs(i).ign = objs(i).ign || v<wRng(1) || v>wRng(2); end; end
if(~isempty(hRng)), for i=1:n, v=objs(i).bb(4);
objs(i).ign = objs(i).ign || v<hRng(1) || v>hRng(2); end; end
if(~isempty(oRng)), for i=1:n, v=objs(i).ang; if(v>180), v=v-360; end
objs(i).ign = objs(i).ign || v<oRng(1) || v>oRng(2); end; end
if(~isempty(aRng)), for i=1:n, v=objs(i).bb(3)*objs(i).bb(4);
objs(i).ign = objs(i).ign || v<aRng(1) || v>aRng(2); end; end
if(~isempty(arRng)), for i=1:n, v=objs(i).bb(3)/objs(i).bb(4);
objs(i).ign = objs(i).ign || v<arRng(1) || v>arRng(2); end; end
if(~isempty(vRng)), for i=1:n, o=objs(i); bb=o.bb; bbv=o.bbv; %#ok<ALIGN>
if(~o.occ || all(bbv==0)), v=1; elseif(all(bbv==bb)), v=0; else
v=(bbv(3)*bbv(4))/(bb(3)*bb(4)); end
objs(i).ign = objs(i).ign || v<vRng(1) || v>vRng(2); end
end
% finally get extent of each bounding box (not trivial if ang~=0)
if(nargout<=1), return; end; if(n==0), bbs=zeros(0,5); return; end
bbs=double([reshape([objs.bb],4,[]); [objs.ign]]'); ign=bbs(:,5)==1;
for i=1:n, bbs(i,1:4)=bbExtent(bbs(i,1:4),objs(i).ang,ellipse); end
if(~isempty(sqr)), bbs(~ign,:)=bbApply('squarify',bbs(~ign,:),sqr{:}); end
function bb = bbExtent( bb, ang, ellipse )
% get bb that fully contains given oriented bb
if(~ang), return; end
if( ellipse ) % get bb that encompases ellipse (tighter)
x=bbApply('getCenter',bb); a=bb(4)/2; b=bb(3)/2; ang=ang-90;
rx=(a*cosd(ang))^2+(b*sind(ang))^2; rx=abs(rx/sqrt(rx));
ry=(a*sind(ang))^2+(b*cosd(ang))^2; ry=abs(ry/sqrt(ry));
bb=[x(1)-rx x(2)-ry 2*rx 2*ry];
else % get bb that encompases rectangle (looser)
c=cosd(ang); s=sind(ang); R=[c -s; s c]; rs=bb(3:4)/2;
x0=-rs(1); x1=rs(1); y0=-rs(2); y1=rs(2); pc=bb(1:2)+rs;
p=[x0 y0; x1 y0; x1 y1; x0 y1]*R'+pc(ones(4,1),:);
x0=min(p(:,1)); x1=max(p(:,1)); y0=min(p(:,2)); y1=max(p(:,2));
bb=[x0 y0 x1-x0 y1-y0];
end
end
end
function vals = get( objs, name )
% Get object property 'name' (in a standard array).
%
% USAGE
% vals = bbGt( 'get', objs, name )
%
% INPUTS
% objs - [nx1] struct array of objects
% name - property name ('lbl','bb','occ',etc.)
%
% OUTPUTS
% vals - [nxk] array of n values (k=1 or 4)
%
% EXAMPLE
%
% See also bbGt, bbGt>set
nObj=length(objs); if(nObj==0), vals=[]; return; end
switch name
case 'lbl', vals={objs.lbl}';
case 'bb', vals=reshape([objs.bb]',4,[])';
case 'occ', vals=[objs.occ]';
case 'bbv', vals=reshape([objs.bbv]',4,[])';
case 'ign', vals=[objs.ign]';
case 'ang', vals=[objs.ang]';
otherwise, error('unkown type %s',name);
end
end
function objs = set( objs, name, vals )
% Set object property 'name' (with a standard array).
%
% USAGE
% objs = bbGt( 'set', objs, name, vals )
%
% INPUTS
% objs - [nx1] struct array of objects
% name - property name ('lbl','bb','occ',etc.)
% vals - [nxk] array of n values (k=1 or 4)
%
% OUTPUTS
% objs - [nx1] struct array of updated objects
%
% EXAMPLE
%
% See also bbGt, bbGt>get
nObj=length(objs);
switch name
case 'lbl', for i=1:nObj, objs(i).lbl=vals{i}; end
case 'bb', for i=1:nObj, objs(i).bb=vals(i,:); end
case 'occ', for i=1:nObj, objs(i).occ=vals(i); end
case 'bbv', for i=1:nObj, objs(i).bbv=vals(i,:); end
case 'ign', for i=1:nObj, objs(i).ign=vals(i); end
case 'ang', for i=1:nObj, objs(i).ang=vals(i); end
otherwise, error('unkown type %s',name);
end
end
function hs = draw( objs, varargin )
% Draw an ellipse for each labeled object.
%
% USAGE
% hs = bbGt( 'draw', objs, pDraw )
%
% INPUTS
% objs - [nx1] struct array of objects
% pDraw - parameters (struct or name/value pairs)
% .col - ['g'] color or [nx1] array of colors
% .lw - [2] line width
% .ls - ['-'] line style
%
% OUTPUTS
% hs - [nx1] handles to drawn graphic objects
%
% EXAMPLE
%
% See also bbGt
dfs={'col',[],'lw',2,'ls','-'};
[col,lw,ls]=getPrmDflt(varargin,dfs,1);
n=length(objs); hold on; hs=zeros(n,4);
if(isempty(col)), if(n==1), col='g'; else col=hsv(n); end; end
tProp={'FontSize',10,'color','w','FontWeight','bold',...
'VerticalAlignment','bottom'};
for i=1:n
bb=objs(i).bb; ci=col(i,:);
hs(i,1)=text(bb(1),bb(2),objs(i).lbl,tProp{:});
x=bbApply('getCenter',bb); r=bb(3:4)/2; a=objs(i).ang/180*pi-pi/2;
[hs(i,2),hs(i,3),hs(i,4)]=plotEllipse(x(2),x(1),r(2),r(1),a,ci,[],lw,ls);
end; hold off;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [fs,fs0] = getFiles( dirs, f0, f1 )
% Get all corresponding files in given directories.
%
% The first dir in 'dirs' serves as the baseline dir. getFiles() returns
% all files in the baseline dir and all corresponding files in the
% remaining dirs to the files in the baseline dir, in the same order. Two
% files are in correspondence if they have the same base name (regardless
% of extension). For example, given a file named "name.jpg", a
% corresponding file may be named "name.txt" or "name.jpg.txt". Every file
% in the baseline dir must have a matching file in the remaining dirs.
%
% USAGE
% [fs,fs0] = bbGt('getFiles', dirs, [f0], [f1] )
%
% INPUTS
% dirs - {1xm} list of m directories
% f0 - [1] index of first file in baseline dir to use
% f1 - [inf] index of last file in baseline dir to use
%
% OUTPUTS
% fs - {mxn} list of full file names in each dir
% fs0 - {1xn} list of file names without path or extensions
%
% EXAMPLE
%
% See also bbGt
if(nargin<2 || isempty(f0)), f0=1; end
if(nargin<3 || isempty(f1)), f1=inf; end
m=length(dirs); assert(m>0); sep=filesep;
for d=1:m, dir1=dirs{d}; dir1(dir1=='\')=sep; dir1(dir1=='/')=sep;
if(dir1(end)==sep), dir1(end)=[]; end; dirs{d}=dir1; end
[fs0,fs1] = getFiles0(dirs{1},f0,f1,sep);
n1=length(fs0); fs=cell(m,n1); fs(1,:)=fs1;
for d=2:m, fs(d,:)=getFiles1(dirs{d},fs0,sep); end
function [fs0,fs1] = getFiles0( dir1, f0, f1, sep )
% get fs1 in dir1 (and fs0 without path or extension)
fs1=dir([dir1 sep '*']); fs1={fs1.name}; fs1=fs1(3:end);
fs1=fs1(f0:min(f1,end)); fs0=fs1; n=length(fs0);
if(n==0), error('No files found in baseline dir %s.',dir1); end
for i=1:n, fs1{i}=[dir1 sep fs0{i}]; end
n=length(fs0); for i=1:n, f=fs0{i};
f(find(f=='.',1,'first'):end)=[]; fs0{i}=f; end
end
function fs1 = getFiles1( dir1, fs0, sep )
% get fs1 in dir1 corresponding to fs0
n=length(fs0); fs1=cell(1,n); i2=0; i1=0;
fs2=dir(dir1); fs2={fs2.name}; n2=length(fs2);
eMsg='''%s'' has no corresponding file in %s.';
for i0=1:n, r=length(fs0{i0}); match=0;
while(i2<n2), i2=i2+1; if(strcmpi(fs0{i0},fs2{i2}(1:min(end,r))))
i1=i1+1; fs1{i1}=fs2{i2}; match=1; break; end; end
if(~match), error(eMsg,fs0{i0},dir1); end
end
for i1=1:n, fs1{i1}=[dir1 sep fs1{i1}]; end
end
end
function fs = copyFiles( fs, dirs )
% Copy corresponding files into given directories.
%
% Useful for splitting data into training, validation and testing sets.
% See also bbGt>getFiles for obtaining a set of corresponding files.
%
% USAGE
% fs = bbGt( 'copyFiles', fs, dirs )
%
% INPUTS
% fs - {mxn} list of full file names in each dir
% dirs - {1xm} list of m target directories
%
% OUTPUTS
% fs - {mxn} list of full file names of copied files
%
% EXAMPLE
%
% See also bbGt, bbGt>getFiles
[m,n]=size(fs); assert(numel(dirs)==m); if(n==0), return; end
for d=1:m
if(~exist(dirs{d},'dir')), mkdir(dirs{d}); end
for i=1:n, f=fs{d,i}; j=[0 find(f=='/' | f=='\')]; j=j(end);
fs{d,i}=[dirs{d} '/' f(j+1:end)]; copyfile(f,fs{d,i}); end
end
end
function [gt0,dt0] = loadAll( gtDir, dtDir, pLoad )
% Load all ground truth and detection bbs in given directories.
%
% Loads each ground truth (gt) annotation in gtDir and the corresponding
% detection (dt) in dtDir. gt and dt files must correspond according to
% getFiles(). Alternatively, dtDir may be a filename of a single text file
% that contains the detection results across all images.
%
% Each dt should be a text file where each row contains 5 numbers
% representing a bb (left/top/width/height/score). If dtDir is a text file,
% it should contain the detection results across the full set of images. In
% this case each row in the text file should have an extra leading column
% specifying the image id: (imgId/left/top/width/height/score).
%
% The output of this function can be used in bbGt>evalRes().
%
% USAGE
% [gt0,dt0] = bbGt( 'loadAll', gtDir, [dtDir], [pLoad] )
%
% INPUTS
% gtDir - location of ground truth
% dtDir - [] optional location of detections
% pLoad - {} params for bbGt>bbLoad() (determine format/filtering)
%
% OUTPUTS
% gt0 - {1xn} loaded ground truth bbs (each is a mx5 array of bbs)
% dt0 - {1xn} loaded detections (each is a mx5 array of bbs)
%
% EXAMPLE
%
% See also bbGt, bbGt>getFiles, bbGt>evalRes
% get list of files
if(nargin<2), dtDir=[]; end
if(nargin<3), pLoad={}; end
if(isempty(dtDir)), fs=getFiles({gtDir}); gtFs=fs(1,:); else
dtFile=length(dtDir)>4 && strcmp(dtDir(end-3:end),'.txt');
if(dtFile), dirs={gtDir}; else dirs={gtDir,dtDir}; end
fs=getFiles(dirs); gtFs=fs(1,:);
if(dtFile), dtFs=dtDir; else dtFs=fs(2,:); end
end
% load ground truth
persistent keyPrv gtPrv; key={gtDir,pLoad}; n=length(gtFs);
if(isequal(key,keyPrv)), gt0=gtPrv; else gt0=cell(1,n);
for i=1:n, [~,gt0{i}]=bbLoad(gtFs{i},pLoad); end
gtPrv=gt0; keyPrv=key;
end
% load detections
if(isempty(dtDir) || nargout<=1), dt0=cell(0); return; end
if(iscell(dtFs)), dt0=cell(1,n);
for i=1:n, dt1=load(dtFs{i},'-ascii');
if(numel(dt1)==0), dt1=zeros(0,5); end; dt0{i}=dt1(:,1:5); end
else
dt1=load(dtFs,'-ascii'); if(numel(dt1)==0), dt1=zeros(0,6); end
ids=dt1(:,1); assert(max(ids)<=n);
dt0=cell(1,n); for i=1:n, dt0{i}=dt1(ids==i,2:6); end
end
end
function [gt,dt] = evalRes( gt0, dt0, thr, mul )
% Evaluates detections against ground truth data.
%
% Uses modified Pascal criteria that allows for "ignore" regions. The
% Pascal criteria states that a ground truth bounding box (gtBb) and a
% detected bounding box (dtBb) match if their overlap area (oa):
% oa(gtBb,dtBb) = area(intersect(gtBb,dtBb)) / area(union(gtBb,dtBb))
% is over a sufficient threshold (typically .5). In the modified criteria,
% the dtBb can match any subregion of a gtBb set to "ignore". Choosing
% gtBb' in gtBb that most closely matches dtBb can be done by using
% gtBb'=intersect(dtBb,gtBb). Computing oa(gtBb',dtBb) is equivalent to
% oa'(gtBb,dtBb) = area(intersect(gtBb,dtBb)) / area(dtBb)
% For gtBb set to ignore the above formula for oa is used.
%
% Highest scoring detections are matched first. Matches to standard,
% (non-ignore) gtBb are preferred. Each dtBb and gtBb may be matched at
% most once, except for ignore-gtBb which can be matched multiple times.
% Unmatched dtBb are false-positives, unmatched gtBb are false-negatives.
% Each match between a dtBb and gtBb is a true-positive, except matches
% between dtBb and ignore-gtBb which do not affect the evaluation criteria.
%
% In addition to taking gt/dt results on a single image, evalRes() can take
% cell arrays of gt/dt bbs, in which case evaluation proceeds on each
% element. Use bbGt>loadAll() to load gt/dt for multiple images.
%
% Each gt/dt output row has a flag match that is either -1/0/1:
% for gt: -1=ignore, 0=fn [unmatched], 1=tp [matched]
% for dt: -1=ignore, 0=fp [unmatched], 1=tp [matched]
%
% USAGE
% [gt, dt] = bbGt( 'evalRes', gt0, dt0, [thr], [mul] )
%
% INPUTS
% gt0 - [mx5] ground truth array with rows [x y w h ignore]
% dt0 - [nx5] detection results array with rows [x y w h score]
% thr - [.5] the threshold on oa for comparing two bbs
% mul - [0] if true allow multiple matches to each gt
%
% OUTPUTS
% gt - [mx5] ground truth results [x y w h match]
% dt - [nx6] detection results [x y w h score match]
%
% EXAMPLE
%
% See also bbGt, bbGt>compOas, bbGt>loadAll
% get parameters
if(nargin<3 || isempty(thr)), thr=.5; end
if(nargin<4 || isempty(mul)), mul=0; end
% if gt0 and dt0 are cell arrays run on each element in turn
if( iscell(gt0) && iscell(dt0) ), n=length(gt0);
assert(length(dt0)==n); gt=cell(1,n); dt=gt;
for i=1:n, [gt{i},dt{i}] = evalRes(gt0{i},dt0{i},thr,mul); end; return;
end
% check inputs
if(isempty(gt0)), gt0=zeros(0,5); end
if(isempty(dt0)), dt0=zeros(0,5); end
assert( size(dt0,2)==5 ); nd=size(dt0,1);
assert( size(gt0,2)==5 ); ng=size(gt0,1);
% sort dt highest score first, sort gt ignore last
[~,ord]=sort(dt0(:,5),'descend'); dt0=dt0(ord,:);
[~,ord]=sort(gt0(:,5),'ascend'); gt0=gt0(ord,:);
gt=gt0; gt(:,5)=-gt(:,5); dt=dt0; dt=[dt zeros(nd,1)];
% Attempt to match each (sorted) dt to each (sorted) gt
oa = compOas( dt(:,1:4), gt(:,1:4), gt(:,5)==-1 );
for d=1:nd
bstOa=thr; bstg=0; bstm=0; % info about best match so far
for g=1:ng
% if this gt already matched, continue to next gt
m=gt(g,5); if( m==1 && ~mul ), continue; end
% if dt already matched, and on ignore gt, nothing more to do
if( bstm~=0 && m==-1 ), break; end
% compute overlap area, continue to next gt unless better match made
if(oa(d,g)<bstOa), continue; end
% match successful and best so far, store appropriately
bstOa=oa(d,g); bstg=g; if(m==0), bstm=1; else bstm=-1; end
end; g=bstg; m=bstm;
% store type of match for both dt and gt
if(m==-1), dt(d,6)=m; elseif(m==1), gt(g,5)=m; dt(d,6)=m; end
end
end
function [hs,hImg] = showRes( I, gt, dt, varargin )
% Display evaluation results for given image.
%
% USAGE
% [hs,hImg] = bbGt( 'showRes', I, gt, dt, varargin )
%
% INPUTS
% I - image to display, image filename, or []
% gt - first output of evalRes()
% dt - second output of evalRes()
% varargin - additional parameters (struct or name/value pairs)
% .evShow - [1] if true show results of evaluation
% .gtShow - [1] if true show ground truth
% .dtShow - [1] if true show detections
% .cols - ['krg'] colors for ignore/mistake/correct
% .gtLs - ['-'] line style for gt bbs
% .dtLs - ['--'] line style for dt bbs
% .lw - [3] line width
%
% OUTPUTS
% hs - handles to bbs and text labels
% hImg - handle for image graphics object
%
% EXAMPLE
%
% See also bbGt, bbGt>evalRes
dfs={'evShow',1,'gtShow',1,'dtShow',1,'cols','krg',...
'gtLs','-','dtLs','--','lw',3};
[evShow,gtShow,dtShow,cols,gtLs,dtLs,lw]=getPrmDflt(varargin,dfs,1);
% optionally display image
if(ischar(I)), I=imread(I); end
if(~isempty(I)), hImg=im(I,[],0); title(''); end
% display bbs with or w/o color coding based on output of evalRes
hold on; hs=cell(1,1000); k=0;
if( evShow )
if(gtShow), for i=1:size(gt,1), k=k+1;
hs{k}=bbApply('draw',gt(i,1:4),cols(gt(i,5)+2),lw,gtLs); end; end
if(dtShow), for i=1:size(dt,1), k=k+1;
hs{k}=bbApply('draw',dt(i,1:5),cols(dt(i,6)+2),lw,dtLs); end; end
else
if(gtShow), k=k+1; hs{k}=bbApply('draw',gt(:,1:4),cols(3),lw,gtLs); end
if(dtShow), k=k+1; hs{k}=bbApply('draw',dt(:,1:5),cols(3),lw,dtLs); end
end
hs=[hs{:}]; hold off;
end
function [xs,ys,score,ref] = compRoc( gt, dt, roc, ref )
% Compute ROC or PR based on outputs of evalRes on multiple images.
%
% ROC="Receiver operating characteristic"; PR="Precision Recall"
% Also computes result at reference points (ref):
% which for ROC curves is the *detection* rate at reference *FPPI*
% which for PR curves is the *precision* at reference *recall*
% Note, FPPI="false positive per image"
%
% USAGE
% [xs,ys,score,ref] = bbGt( 'compRoc', gt, dt, roc, ref )
%
% INPUTS
% gt - {1xn} first output of evalRes() for each image
% dt - {1xn} second output of evalRes() for each image
% roc - [1] if 1 compue ROC else compute PR
% ref - [] reference points for ROC or PR curve
%
% OUTPUTS
% xs - x coords for curve: ROC->FPPI; PR->recall
% ys - y coords for curve: ROC->TP; PR->precision
% score - detection scores corresponding to each (x,y)
% ref - recall or precision at each reference point
%
% EXAMPLE
%
% See also bbGt, bbGt>evalRes
% get additional parameters
if(nargin<3 || isempty(roc)), roc=1; end
if(nargin<4 || isempty(ref)), ref=[]; end
% convert to single matrix, discard ignore bbs
nImg=length(gt); assert(length(dt)==nImg);
gt=cat(1,gt{:}); gt=gt(gt(:,5)~=-1,:);
dt=cat(1,dt{:}); dt=dt(dt(:,6)~=-1,:);
% compute results
if(size(dt,1)==0), xs=0; ys=0; score=0; ref=ref*0; return; end
m=length(ref); np=size(gt,1); score=dt(:,5); tp=dt(:,6);
[score,order]=sort(score,'descend'); tp=tp(order);
fp=double(tp~=1); fp=cumsum(fp); tp=cumsum(tp);
if( roc )
xs=fp/nImg; ys=tp/np; xs1=[-inf; xs]; ys1=[0; ys];
for i=1:m, j=find(xs1<=ref(i)); ref(i)=ys1(j(end)); end
else
xs=tp/np; ys=tp./(fp+tp); xs1=[xs; inf]; ys1=[ys; 0];
for i=1:m, j=find(xs1>=ref(i)); ref(i)=ys1(j(1)); end
end
end
function [Is,scores,imgIds] = cropRes( gt, dt, imFs, varargin )
% Extract true or false positives or negatives for visualization.
%
% USAGE
% [Is,scores,imgIds] = bbGt( 'cropRes', gt, dt, imFs, varargin )
%
% INPUTS
% gt - {1xN} first output of evalRes() for each image
% dt - {1xN} second output of evalRes() for each image
% imFs - {1xN} name of each image
% varargin - additional parameters (struct or name/value pairs)
% .dims - ['REQ'] target dimensions for extracted windows
% .pad - [0] padding amount for cropping
% .type - ['fp'] one of: 'fp', 'fn', 'tp', 'dt'
% .n - [100] max number of windows to extract
% .show - [1] figure for displaying results (or 0)
% .fStr - ['%0.1f'] label{i}=num2str(score(i),fStr)
% .embed - [0] if true embed dt/gt bbs into cropped windows
%
% OUTPUTS
% Is - [dimsxn] extracted image windows
% scores - [1xn] detection score for each bb unless 'fn'
% imgIds - [1xn] image id for each cropped window
%
% EXAMPLE
%
% See also bbGt, bbGt>evalRes
dfs={'dims','REQ','pad',0,'type','fp','n',100,...
'show',1,'fStr','%0.1f','embed',0};
[dims,pad,type,n,show,fStr,embed]=getPrmDflt(varargin,dfs,1);
N=length(imFs); assert(length(gt)==N && length(dt)==N);
% crop patches either in gt or dt according to type
switch type
case 'fn', bbs=gt; keep=@(bbs) bbs(:,5)==0;
case 'fp', bbs=dt; keep=@(bbs) bbs(:,6)==0;
case 'tp', bbs=dt; keep=@(bbs) bbs(:,6)==1;
case 'dt', bbs=dt; keep=@(bbs) bbs(:,6)>=0;
otherwise, error('unknown type: %s',type);
end
% create ids that will map each bb to correct name
ms=zeros(1,N); for i=1:N, ms(i)=size(bbs{i},1); end; cms=[0 cumsum(ms)];
ids=zeros(1,sum(ms)); for i=1:N, ids(cms(i)+1:cms(i+1))=i; end
% flatten bbs and keep relevent subset
bbs=cat(1,bbs{:}); K=keep(bbs); bbs=bbs(K,:); ids=ids(K); n=min(n,sum(K));
% reorder bbs appropriately
if(~strcmp(type,'fn')), [~,ord]=sort(bbs(:,5),'descend'); else
if(size(bbs,1)<n), ord=randperm(size(bbs,1)); else ord=1:n; end; end
bbs=bbs(ord(1:n),:); ids=ids(ord(1:n));
% extract patches from each image
if(n==0), Is=[]; scores=[]; imgIds=[]; return; end;
Is=cell(1,n); scores=zeros(1,n); imgIds=zeros(1,n);
if(any(pad>0)), dims1=dims.*(1+pad); rs=dims1./dims; dims=dims1; end
if(any(pad>0)), bbs=bbApply('resize',bbs,rs(1),rs(2)); end
for i=1:N
locs=find(ids==i); if(isempty(locs)), continue; end; I=imread(imFs{i});
if( embed )
if(any(strcmp(type,{'fp','dt'}))), bbs1=gt{i};
else bbs1=dt{i}(:,[1:4 6]); end
I=bbApply('embed',I,bbs1(bbs1(:,5)==0,1:4),'col',[255 0 0]);
I=bbApply('embed',I,bbs1(bbs1(:,5)==1,1:4),'col',[0 255 0]);
end
Is1=bbApply('crop',I,bbs(locs,1:4),'replicate',dims);
for j=1:length(locs), Is{locs(j)}=Is1{j}; end;
scores(locs)=bbs(locs,5); imgIds(locs)=i;
end; Is=cell2array(Is);
% optionally display
if(~show), return; end; figure(show); pMnt={'hasChn',size(Is1{1},3)>1};
if(isempty(fStr)), montage2(Is,pMnt); title(type); return; end
ls=cell(1,n); for i=1:n, ls{i}=int2str2(imgIds(i)); end
if(~strcmp(type,'fn'))
for i=1:n, ls{i}=[ls{i} '/' num2str(scores(i),fStr)]; end; end
montage2(Is,[pMnt 'labels' {ls}]); title(type);
end
function oa = compOas( dt, gt, ig )
% Computes (modified) overlap area between pairs of bbs.
%
% Uses modified Pascal criteria with "ignore" regions. The overlap area
% (oa) of a ground truth (gt) and detected (dt) bb is defined as:
% oa(gt,dt) = area(intersect(dt,dt)) / area(union(gt,dt))
% In the modified criteria, a gt bb may be marked as "ignore", in which
% case the dt bb can can match any subregion of the gt bb. Choosing gt' in
% gt that most closely matches dt can be done using gt'=intersect(dt,gt).
% Computing oa(gt',dt) is equivalent to:
% oa'(gt,dt) = area(intersect(gt,dt)) / area(dt)
%
% USAGE
% oa = bbGt( 'compOas', dt, gt, [ig] )
%
% INPUTS
% dt - [mx4] detected bbs
% gt - [nx4] gt bbs
% ig - [nx1] 0/1 ignore flags (0 by default)
%
% OUTPUTS
% oas - [m x n] overlap area between each gt and each dt bb
%
% EXAMPLE
% dt=[0 0 10 10]; gt=[0 0 20 20];
% oa0 = bbGt('compOas',dt,gt,0)
% oa1 = bbGt('compOas',dt,gt,1)
%
% See also bbGt, bbGt>evalRes
m=size(dt,1); n=size(gt,1); oa=zeros(m,n);
if(nargin<3), ig=zeros(n,1); end
de=dt(:,[1 2])+dt(:,[3 4]); da=dt(:,3).*dt(:,4);
ge=gt(:,[1 2])+gt(:,[3 4]); ga=gt(:,3).*gt(:,4);
for i=1:m
for j=1:n
w=min(de(i,1),ge(j,1))-max(dt(i,1),gt(j,1)); if(w<=0), continue; end
h=min(de(i,2),ge(j,2))-max(dt(i,2),gt(j,2)); if(h<=0), continue; end
t=w*h; if(ig(j)), u=da(i); else u=da(i)+ga(j)-t; end; oa(i,j)=t/u;
end
end
end
function oa = compOa( dt, gt, ig )
% Optimized version of compOas for a single pair of bbs.
%
% USAGE
% oa = bbGt( 'compOa', dt, gt, ig )
%
% INPUTS
% dt - [1x4] detected bb
% gt - [1x4] gt bb
% ig - 0/1 ignore flag
%
% OUTPUTS
% oa - overlap area between gt and dt bb
%
% EXAMPLE
% dt=[0 0 10 10]; gt=[0 0 20 20];
% oa0 = bbGt('compOa',dt,gt,0)
% oa1 = bbGt('compOa',dt,gt,1)
%
% See also bbGt, bbGt>compOas
w=min(dt(3)+dt(1),gt(3)+gt(1))-max(dt(1),gt(1)); if(w<=0),oa=0; return; end
h=min(dt(4)+dt(2),gt(4)+gt(2))-max(dt(2),gt(2)); if(h<=0),oa=0; return; end
i=w*h; if(ig),u=dt(3)*dt(4); else u=dt(3)*dt(4)+gt(3)*gt(4)-i; end; oa=i/u;
end
|
github
|
3arbouch/PersonDetection-master
|
bbApply.m
|
.m
|
PersonDetection-master/Source/toolbox/detector/bbApply.m
| 21,195 |
utf_8
|
cc9744e55c6b8442486ba7f71e3f84ce
|
function varargout = bbApply( action, varargin )
% Functions for manipulating bounding boxes (bb).
%
% A bounding box (bb) is also known as a position vector or a rectangle
% object. It is a four element vector with the fields: [x y w h]. A set of
% n bbs can be stores as an [nx4] array, most funcitons below can handle
% either a single or multiple bbs. In addtion, typically [nxm] inputs with
% m>4 are ok (with the additional columns ignored/copied to the output).
%
% bbApply contains a number of utility functions for working with bbs. The
% format for accessing the various utility functions is:
% outputs = bbApply( 'action', inputs );
% The list of functions and help for each is given below. Also, help on
% individual subfunctions can be accessed by: "help bbApply>action".
%
% Compute area of bbs.
% bb = bbApply( 'area', bb )
% Shift center of bbs.
% bb = bbApply( 'shift', bb, xdel, ydel )
% Get center of bbs.
% cen = bbApply( 'getCenter', bb )
% Get bb at intersection of bb1 and bb2 (may be empty).
% bb = bbApply( 'intersect', bb1, bb2 )
% Get bb that is union of bb1 and bb2 (smallest bb containing both).
% bb = bbApply( 'union', bb1, bb2 )
% Resize the bbs (without moving their centers).
% bb = bbApply( 'resize', bb, hr, wr, [ar] )
% Fix bb aspect ratios (without moving the bb centers).
% bbr = bbApply( 'squarify', bb, flag, [ar] )
% Draw single or multiple bbs to image (calls rectangle()).
% hs = bbApply( 'draw', bb, [col], [lw], [ls], [prop], [ids] )
% Embed single or multiple bbs directly into image.
% I = bbApply( 'embed', I, bb, [varargin] )
% Crop image regions from I encompassed by bbs.
% [patches, bbs] = bbApply('crop',I,bb,[padEl],[dims])
% Convert bb relative to absolute coordinates and vice-versa.
% bb = bbApply( 'convert', bb, bbRef, isAbs )
% Randomly generate bbs that fall in a specified region.
% bbs = bbApply( 'random', pRandom )
% Convert weighted mask to bbs.
% bbs = bbApply('frMask',M,bbw,bbh,[thr])
% Create weighted mask encoding bb centers (or extent).
% M = bbApply('toMask',bbs,w,h,[fill],[bgrd])
%
% USAGE
% varargout = bbApply( action, varargin );
%
% INPUTS
% action - string specifying action
% varargin - depends on action, see above
%
% OUTPUTS
% varargout - depends on action, see above
%
% EXAMPLE
%
% See also bbApply>area bbApply>shift bbApply>getCenter bbApply>intersect
% bbApply>union bbApply>resize bbApply>squarify bbApply>draw bbApply>crop
% bbApply>convert bbApply>random bbApply>frMask bbApply>toMask
%
% Piotr's Computer Vision Matlab Toolbox Version 3.30
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%#ok<*DEFNU>
varargout = cell(1,max(1,nargout));
[varargout{:}] = feval(action,varargin{:});
end
function a = area( bb )
% Compute area of bbs.
%
% USAGE
% bb = bbApply( 'area', bb )
%
% INPUTS
% bb - [nx4] original bbs
%
% OUTPUTS
% a - [nx1] area of each bb
%
% EXAMPLE
% a = bbApply('area', [0 0 10 10])
%
% See also bbApply
a=prod(bb(:,3:4),2);
end
function bb = shift( bb, xdel, ydel )
% Shift center of bbs.
%
% USAGE
% bb = bbApply( 'shift', bb, xdel, ydel )
%
% INPUTS
% bb - [nx4] original bbs
% xdel - amount to shift x coord of each bb left
% ydel - amount to shift y coord of each bb up
%
% OUTPUTS
% bb - [nx4] shifted bbs
%
% EXAMPLE
% bb = bbApply('shift', [0 0 10 10], 1, 2)
%
% See also bbApply
bb(:,1)=bb(:,1)-xdel; bb(:,2)=bb(:,2)-ydel;
end
function cen = getCenter( bb )
% Get center of bbs.
%
% USAGE
% cen = bbApply( 'getCenter', bb )
%
% INPUTS
% bb - [nx4] original bbs
%
% OUTPUTS
% cen - [nx1] centers of bbs
%
% EXAMPLE
% cen = bbApply('getCenter', [0 0 10 10])
%
% See also bbApply
cen=bb(:,1:2)+bb(:,3:4)/2;
end
function bb = intersect( bb1, bb2 )
% Get bb at intersection of bb1 and bb2 (may be empty).
%
% USAGE
% bb = bbApply( 'intersect', bb1, bb2 )
%
% INPUTS
% bb1 - [nx4] first set of bbs
% bb2 - [nx4] second set of bbs
%
% OUTPUTS
% bb - [nx4] intersection of bbs
%
% EXAMPLE
% bb = bbApply('intersect', [0 0 10 10], [5 5 10 10])
%
% See also bbApply bbApply>union
n1=size(bb1,1); n2=size(bb2,1);
if(n1==0 || n2==0), bb=zeros(0,4); return, end
if(n1==1 && n2>1), bb1=repmat(bb1,n2,1); n1=n2; end
if(n2==1 && n1>1), bb2=repmat(bb2,n1,1); n2=n1; end
assert(n1==n2);
lcsE=min(bb1(:,1:2)+bb1(:,3:4),bb2(:,1:2)+bb2(:,3:4));
lcsS=max(bb1(:,1:2),bb2(:,1:2)); empty=any(lcsE<lcsS,2);
bb=[lcsS lcsE-lcsS]; bb(empty,:)=0;
end
function bb = union( bb1, bb2 )
% Get bb that is union of bb1 and bb2 (smallest bb containing both).
%
% USAGE
% bb = bbApply( 'union', bb1, bb2 )
%
% INPUTS
% bb1 - [nx4] first set of bbs
% bb2 - [nx4] second set of bbs
%
% OUTPUTS
% bb - [nx4] intersection of bbs
%
% EXAMPLE
% bb = bbApply('union', [0 0 10 10], [5 5 10 10])
%
% See also bbApply bbApply>intersect
n1=size(bb1,1); n2=size(bb2,1);
if(n1==0 || n2==0), bb=zeros(0,4); return, end
if(n1==1 && n2>1), bb1=repmat(bb1,n2,1); n1=n2; end
if(n2==1 && n1>1), bb2=repmat(bb2,n1,1); n2=n1; end
assert(n1==n2);
lcsE=max(bb1(:,1:2)+bb1(:,3:4),bb2(:,1:2)+bb2(:,3:4));
lcsS=min(bb1(:,1:2),bb2(:,1:2));
bb=[lcsS lcsE-lcsS];
end
function bb = resize( bb, hr, wr, ar )
% Resize the bbs (without moving their centers).
%
% If wr>0 or hr>0, the w/h of each bb is adjusted in the following order:
% if(hr~=0), h=h*hr; end
% if(wr~=0), w=w*wr; end
% if(hr==0), h=w/ar; end
% if(wr==0), w=h*ar; end
% Only one of hr/wr may be set to 0, and then only if ar>0. If, however,
% hr=wr=0 and ar>0 then resizes bbs such that areas and centers are
% preserved but aspect ratio becomes ar.
%
% USAGE
% bb = bbApply( 'resize', bb, hr, wr, [ar] )
%
% INPUTS
% bb - [nx4] original bbs
% hr - ratio by which to multiply height (or 0)
% wr - ratio by which to multiply width (or 0)
% ar - [0] target aspect ratio (used only if hr=0 or wr=0)
%
% OUTPUT
% bb - [nx4] the output resized bbs
%
% EXAMPLE
% bb = bbApply('resize',[0 0 1 1],1.2,0,.5) % h'=1.2*h; w'=h'/2;
%
% See also bbApply, bbApply>squarify
if(nargin<4), ar=0; end; assert(size(bb,2)>=4);
assert((hr>0&&wr>0)||ar>0);
% preserve area and center, set aspect ratio
if(hr==0 && wr==0), a=sqrt(bb(:,3).*bb(:,4)); ar=sqrt(ar);
d=a*ar-bb(:,3); bb(:,1)=bb(:,1)-d/2; bb(:,3)=bb(:,3)+d;
d=a/ar-bb(:,4); bb(:,2)=bb(:,2)-d/2; bb(:,4)=bb(:,4)+d; return;
end
% possibly adjust h/w based on hr/wr
if(hr~=0), d=(hr-1)*bb(:,4); bb(:,2)=bb(:,2)-d/2; bb(:,4)=bb(:,4)+d; end
if(wr~=0), d=(wr-1)*bb(:,3); bb(:,1)=bb(:,1)-d/2; bb(:,3)=bb(:,3)+d; end
% possibly adjust h/w based on ar and NEW h/w
if(~hr), d=bb(:,3)/ar-bb(:,4); bb(:,2)=bb(:,2)-d/2; bb(:,4)=bb(:,4)+d; end
if(~wr), d=bb(:,4)*ar-bb(:,3); bb(:,1)=bb(:,1)-d/2; bb(:,3)=bb(:,3)+d; end
end
function bbr = squarify( bb, flag, ar )
% Fix bb aspect ratios (without moving the bb centers).
%
% The w or h of each bb is adjusted so that w/h=ar.
% The parameter flag controls whether w or h should change:
% flag==0: expand bb to given ar
% flag==1: shrink bb to given ar
% flag==2: use original w, alter h
% flag==3: use original h, alter w
% flag==4: preserve area, alter w and h
% If ar==1 (the default), always converts bb to a square, hence the name.
%
% USAGE
% bbr = bbApply( 'squarify', bb, flag, [ar] )
%
% INPUTS
% bb - [nx4] original bbs
% flag - controls whether w or h should change
% ar - [1] desired aspect ratio
%
% OUTPUT
% bbr - the output 'squarified' bbs
%
% EXAMPLE
% bbr = bbApply('squarify',[0 0 1 2],0)
%
% See also bbApply, bbApply>resize
if(nargin<3 || isempty(ar)), ar=1; end; bbr=bb;
if(flag==4), bbr=resize(bb,0,0,ar); return; end
for i=1:size(bb,1), p=bb(i,1:4);
usew = (flag==0 && p(3)>p(4)*ar) || (flag==1 && p(3)<p(4)*ar) || flag==2;
if(usew), p=resize(p,0,1,ar); else p=resize(p,1,0,ar); end; bbr(i,1:4)=p;
end
end
function hs = draw( bb, col, lw, ls, prop, ids )
% Draw single or multiple bbs to image (calls rectangle()).
%
% To draw bbs aligned with pixel boundaries, subtract .5 from the x and y
% coordinates (since pixel centers are located at integer locations).
%
% USAGE
% hs = bbApply( 'draw', bb, [col], [lw], [ls], [prop], [ids] )
%
% INPUTS
% bb - [nx4] standard bbs or [nx5] weighted bbs
% col - ['g'] color or [kx1] array of colors
% lw - [2] LineWidth for rectangle
% ls - ['-'] LineStyle for rectangle
% prop - [] other properties for rectangle
% ids - [ones(1,n)] id in [1,k] for each bb into colors array
%
% OUTPUT
% hs - [nx1] handles to drawn rectangles (and labels)
%
% EXAMPLE
% im(rand(3)); bbApply('draw',[1.5 1.5 1 1 .5],'g');
%
% See also bbApply, bbApply>embed, rectangle
[n,m]=size(bb); if(n==0), hs=[]; return; end
if(nargin<2 || isempty(col)), col=[]; end
if(nargin<3 || isempty(lw)), lw=2; end
if(nargin<4 || isempty(ls)), ls='-'; end
if(nargin<5 || isempty(prop)), prop={}; end
if(nargin<6 || isempty(ids)), ids=ones(1,n); end
% prepare display properties
prop=['LineWidth' lw 'LineStyle' ls prop 'EdgeColor'];
tProp={'FontSize',10,'color','w','FontWeight','bold',...
'VerticalAlignment','bottom'}; k=max(ids);
if(isempty(col)), if(k==1), col='g'; else col=hsv(k); end; end
if(size(col,1)<k), ids=ones(1,n); end; hs=zeros(1,n);
% draw rectangles and optionally labels
for b=1:n, hs(b)=rectangle('Position',bb(b,1:4),prop{:},col(ids(b),:)); end
if(m==4), return; end; hs=[hs zeros(1,n)]; bb=double(bb);
for b=1:n, hs(b+n)=text(bb(b,1),bb(b,2),num2str(bb(b,5),4),tProp{:}); end
end
function I = embed( I, bb, varargin )
% Embed single or multiple bbs directly into image.
%
% USAGE
% I = bbApply( 'embed', I, bb, varargin )
%
% INPUTS
% I - input image
% bb - [nx4] or [nx5] input bbs
% varargin - additional params (struct or name/value pairs)
% .col - [0 255 0] color for rectangle or nx3 array of colors
% .lw - [3] width for rectangle in pixels
% .fh - [35] font height (if displaying weight), may be 0
% .fcol - [255 0 0] font color or nx3 array of colors
%
% OUTPUT
% I - output image
%
% EXAMPLE
% I=imResample(imread('cameraman.tif'),2); bb=[200 70 70 90 0.25];
% J=bbApply('embed',I,bb,'col',[0 0 255],'lw',8,'fh',30); figure(1); im(J)
% K=bbApply('embed',J,bb,'col',[0 255 0],'lw',2,'fh',30); figure(2); im(K)
%
% See also bbApply, bbApply>draw, char2img
% get additional parameters
dfs={'col',[0 255 0],'lw',3,'fh',35,'fcol',[255 0 0]};
[col,lw,fh,fcol]=getPrmDflt(varargin,dfs,1);
n=size(bb,1); bb(:,1:4)=round(bb(:,1:4));
if(size(col,1)==1), col=col(ones(1,n),:); end
if(size(fcol,1)==1), fcol=fcol(ones(1,n),:); end
if( ismatrix(I) ), I=I(:,:,[1 1 1]); end
% embed each bb
x0=bb(:,1); x1=x0+bb(:,3)-1; y0=bb(:,2); y1=y0+bb(:,4)-1;
j0=floor((lw-1)/2); j1=ceil((lw-1)/2); h=size(I,1); w=size(I,2);
x00=max(1,x0-j0); x01=min(x0+j1,w); x10=max(1,x1-j0); x11=min(x1+j1,w);
y00=max(1,y0-j0); y01=min(y0+j1,h); y10=max(1,y1-j0); y11=min(y1+j1,h);
for b=1:n
for c=1:3, I([y00(b):y01(b) y10(b):y11(b)],x00(b):x11(b),c)=col(b,c); end
for c=1:3, I(y00(b):y11(b),[x00(b):x01(b) x10(b):x11(b)],c)=col(b,c); end
end
% embed text displaying bb score (inside upper-left bb corner)
if(size(bb,2)<5 || fh==0), return; end
bb(:,1:4)=intersect(bb(:,1:4),[1 1 w h]);
for b=1:n
M=char2img(sprintf('%.4g',bb(b,5)),fh); M=M{1}==0; [h,w]=size(M);
y0=bb(b,2); y1=y0+h-1; x0=bb(b,1); x1=x0+w-1;
if( x0>=1 && y0>=1 && x1<=size(I,2) && y1<=size(I,2))
Ir=I(y0:y1,x0:x1,1); Ig=I(y0:y1,x0:x1,2); Ib=I(y0:y1,x0:x1,3);
Ir(M)=fcol(b,1); Ig(M)=fcol(b,2); Ib(M)=fcol(b,3);
I(y0:y1,x0:x1,:)=cat(3,Ir,Ig,Ib);
end
end
end
function [patches, bbs] = crop( I, bbs, padEl, dims )
% Crop image regions from I encompassed by bbs.
%
% The only subtlety is that a pixel centered at location (i,j) would have a
% bb of [j-1/2,i-1/2,1,1]. The -1/2 is because pixels are located at
% integer locations. This is a Matlab convention, to confirm use:
% im(rand(3)); bbApply('draw',[1.5 1.5 1 1],'g')
% If bb contains all integer entries cropping is straightforward. If
% entries are not integers, x=round(x+.499) is used, eg 1.2 actually goes
% to 2 (since it is closer to 1.5 then .5), and likewise for y.
%
% If ~isempty(padEl), image is padded so can extract full bb region (no
% actual padding is done, this is fast). Otherwise bb is intersected with
% the image bb prior to cropping. If padEl is a string ('circular',
% 'replicate', or 'symmetric'), uses padarray to do actual padding (slow).
%
% USAGE
% [patches, bbs] = bbApply('crop',I,bb,[padEl],[dims])
%
% INPUTS
% I - image from which to crop patches
% bbs - bbs that indicate regions to crop
% padEl - [0] value to pad I or [] to indicate no padding (see above)
% dims - [] if specified resize each cropped patch to [w h]
%
% OUTPUTS
% patches - [1xn] cell of cropped image regions
% bbs - actual integer-valued bbs used to crop
%
% EXAMPLE
% I=imread('cameraman.tif'); bb=[-10 -10 100 100];
% p1=bbApply('crop',I,bb); p2=bbApply('crop',I,bb,'replicate');
% figure(1); im(I); figure(2); im(p1{1}); figure(3); im(p2{1});
%
% See also bbApply, ARRAYCROP, PADARRAY, IMRESAMPLE
% get padEl, bound bb to visible region if empty
if( nargin<3 ), padEl=0; end; h=size(I,1); w=size(I,2);
if( nargin<4 ), dims=[]; end;
if(isempty(padEl)), bbs=intersect([.5 .5 w h],bbs); end
% crop each patch in turn
n=size(bbs,1); patches=cell(1,n);
for i=1:n, [patches{i},bbs(i,1:4)]=crop1(bbs(i,1:4)); end
function [patch, bb] = crop1( bb )
% crop single patch (use arrayCrop only if necessary)
lcsS=round(bb([2 1])+.5-.001); lcsE=lcsS+round(bb([4 3]))-1;
if( any(lcsS<1) || lcsE(1)>h || lcsE(2)>w )
if( ischar(padEl) )
pt=max(0,1-lcsS(1)); pb=max(0,lcsE(1)-h);
pl=max(0,1-lcsS(2)); pr=max(0,lcsE(2)-w);
lcsS1=max(1,lcsS); lcsE1=min(lcsE,[h w]);
patch = I(lcsS1(1):lcsE1(1),lcsS1(2):lcsE1(2),:);
patch = padarray(patch,[pt pl],padEl,'pre');
patch = padarray(patch,[pb pr],padEl,'post');
else
if(ndims(I)==3); lcsS=[lcsS 1]; lcsE=[lcsE 3]; end
patch = arrayCrop(I,lcsS,lcsE,padEl);
end
else
patch = I(lcsS(1):lcsE(1),lcsS(2):lcsE(2),:);
end
bb = [lcsS([2 1]) lcsE([2 1])-lcsS([2 1])+1];
if(~isempty(dims)), patch=imResample(patch,[dims(2),dims(1)]); end
end
end
function bb = convert( bb, bbRef, isAbs )
% Convert bb relative to absolute coordinates and vice-versa.
%
% If isAbs==1, bb is assumed to be given in absolute coords, and the output
% is given in coords relative to bbRef. Otherwise, if isAbs==0, bb is
% assumed to be given in coords relative to bbRef and the output is given
% in absolute coords.
%
% USAGE
% bb = bbApply( 'convert', bb, bbRef, isAbs )
%
% INPUTS
% bb - original bb, either in abs or rel coords
% bbRef - reference bb
% isAbs - 1: bb is in abs coords, 0: bb is in rel coords
%
% OUTPUTS
% bb - converted bb
%
% EXAMPLE
% bbRef=[5 5 15 15]; bba=[10 10 5 5];
% bbr = bbApply( 'convert', bba, bbRef, 1 )
% bba2 = bbApply( 'convert', bbr, bbRef, 0 )
%
% See also bbApply
if( isAbs )
bb(1:2)=bb(1:2)-bbRef(1:2);
bb=bb./bbRef([3 4 3 4]);
else
bb=bb.*bbRef([3 4 3 4]);
bb(1:2)=bb(1:2)+bbRef(1:2);
end
end
function bbs = random( varargin )
% Randomly generate bbs that fall in a specified region.
%
% The vector dims defines the region in which bbs are generated. Specify
% dims=[height width] to generate bbs=[x y w h] such that: 1<=x<=width,
% 1<=y<=height, x+w-1<=width, y+h-1<=height. The biggest bb generated can
% be bb=[1 1 width height]. If dims is a three element vector the third
% coordinate is the depth, in this case bbs=[x y w h d] where 1<=d<=depth.
%
% A number of constraints can be specified that control the size and other
% characteristics of the generated bbs. Note that if incompatible
% constraints are specified (e.g. if the maximum width and height are both
% 5 while the minimum area is 100) no bbs will be generated. More
% generally, if fewer than n bbs are generated a warning is displayed.
%
% USAGE
% bbs = bbApply( 'random', pRandom )
%
% INPUTS
% pRandom - parameters (struct or name/value pairs)
% .n - ['REQ'] number of bbs to generate
% .dims - ['REQ'] region in which to generate bbs [height,width]
% .wRng - [1 inf] range for width of bbs (or scalar value)
% .hRng - [1 inf] range for height of bbs (or scalar value)
% .aRng - [1 inf] range for area of bbs
% .arRng - [0 inf] range for aspect ratio (width/height) of bbs
% .unique - [1] if true generate unique bbs
% .maxOverlap - [1] max overlap (intersection/union) between bbs
% .maxIter - [100] max iterations to go w/o changes before giving up
% .show - [0] if true show sample generated bbs
%
% OUTPUTS
% bbs - [nx4] array of randomly generated integer bbs
%
% EXAMPLE
% bbs=bbApply('random','n',50,'dims',[20 20],'arRng',[.5 .5],'show',1);
%
% See also bbApply
% get parameters
rng=[1 inf]; dfs={ 'n','REQ', 'dims','REQ', 'wRng',rng, 'hRng',rng, ...
'aRng',rng, 'arRng',[0 inf], 'unique',1, 'maxOverlap',1, ...
'maxIter',100, 'show',0 };
[n,dims,wRng,hRng,aRng,arRng,uniqueOnly,maxOverlap,maxIter,show] ...
= getPrmDflt(varargin,dfs,1);
if(length(hRng)==1), hRng=[hRng hRng]; end
if(length(wRng)==1), wRng=[wRng wRng]; end
if(length(dims)==3), d=5; else d=4; end
% generate random bbs satisfying constraints
bbs=zeros(0,d); ids=zeros(0,1); n1=min(n*10,1000);
M=max(dims)+1; M=M.^(0:d-1); iter=0; k=0;
tid=ticStatus('generating random bbs',1,2);
while( k<n && iter<maxIter )
ys=1+floor(rand(2,n1)*dims(1)); ys0=min(ys); ys1=max(ys); hs=ys1-ys0+1;
xs=1+floor(rand(2,n1)*dims(2)); xs0=min(xs); xs1=max(xs); ws=xs1-xs0+1;
if(d==5), ds=1+floor(rand(1,n1)*dims(3)); else ds=zeros(0,n1); end
if(arRng(1)==arRng(2)), ws=hs.*arRng(1); end
ars=ws./hs; ws=round(ws); xs1=xs0+ws-1; as=ws.*hs;
kp = ys0>0 & xs0>0 & ys1<=dims(1) & xs1<=dims(2) & ...
hs>=hRng(1) & hs<=hRng(2) & ws>=wRng(1) & ws<=wRng(2) & ...
as>=aRng(1) & as<=aRng(2) & ars>=arRng(1) & ars<=arRng(2);
bbs1=[xs0' ys0' ws' hs' ds']; bbs1=bbs1(kp,:);
k0=k; bbs=[bbs; bbs1]; k=size(bbs,1); %#ok<AGROW>
if( maxOverlap<1 && k ), bbs=bbs(1:k0,:);
for j=1:size(bbs1,1), bbs0=bbs; bb=bbs1(j,:);
if(d==5), bbs=bbs(bbs(:,5)==bb(5),:); end
if(isempty(bbs)), bbs=[bbs0; bb]; continue; end
ws1=min(bbs(:,1)+bbs(:,3),bb(1)+bb(3))-max(bbs(:,1),bb(1));
hs1=min(bbs(:,2)+bbs(:,4),bb(2)+bb(4))-max(bbs(:,2),bb(2));
o=max(0,ws1).*max(0,hs1); o=o./(bbs(:,3).*bbs(:,4)+bb(3).*bb(4)-o);
if(max(o)<=maxOverlap), bbs=[bbs0; bb]; else bbs=bbs0; end
end
elseif( uniqueOnly && k )
ids=[ids; sum(bbs1.*M(ones(1,size(bbs1,1)),:),2)]; %#ok<AGROW>
[ids,o]=sort(ids); bbs=bbs(o,:); kp=[ids(1:end-1)~=ids(2:end); true];
bbs=bbs(kp,:); ids=ids(kp,:);
end
k=size(bbs,1); if(k0==k), iter=iter+1; else iter=0; end
if(k>n), bbs=bbs(randSample(k,n),:); k=n; end;
tocStatus(tid,max(k/n,iter/maxIter));
end
if( k<n ), warning('only generated %i of %i bbs',k,n); n=k; end %#ok<WNTAG>
% optionally display a few bbs
if( show )
k=8; figure(show); im(zeros(dims)); cs=uniqueColors(1,k,0,0);
if(n>k), bbs1=bbs(randsample(n,k),:); else bbs1=bbs; end
bbs1(:,1:2)=bbs1(:,1:2)-.5;
for i=1:min(k,n), rectangle('Position',bbs1(i,:),...
'EdgeColor',cs(i,:),'LineStyle','--'); end
end
end
function bbs = frMask( M, bbw, bbh, thr )
% Convert weighted mask to bbs.
%
% Pixels in mask above given threshold (thr) indicate bb centers.
%
% USAGE
% bbs = bbApply('frMask',M,bbw,bbh,[thr])
%
% INPUTS
% M - mask
% bbw - bb target width
% bbh - bb target height
% thr - [0] mask threshold
%
% OUTPUTS
% bbs - bounding boxes
%
% EXAMPLE
% w=20; h=10; bbw=5; bbh=8; M=double(rand(h,w)); M(M<.95)=0;
% bbs=bbApply('frMask',M,bbw,bbh); M2=bbApply('toMask',bbs,w,h);
% sum(abs(M(:)-M2(:)))
%
% See also bbApply, bbApply>toMask
if(nargin<4), thr=0; end
ids=find(M>thr); ids=ids(:); h=size(M,1);
if(isempty(ids)), bbs=zeros(0,5); return; end
xs=floor((ids-1)/h); ys=ids-xs*h; xs=xs+1;
bbs=[xs-floor(bbw/2) ys-floor(bbh/2)];
bbs(:,3)=bbw; bbs(:,4)=bbh; bbs(:,5)=M(ids);
end
function M = toMask( bbs, w, h, fill, bgrd )
% Create weighted mask encoding bb centers (or extent).
%
% USAGE
% M = bbApply('toMask',bbs,w,h,[fill],[bgrd])
%
% INPUTS
% bbs - bounding boxes
% w - mask target width
% h - mask target height
% fill - [0] if 1 encodes extent of bbs
% bgrd - [0] default value for background pixels
%
% OUTPUTS
% M - hxw mask
%
% EXAMPLE
%
% See also bbApply, bbApply>frMask
if(nargin<4||isempty(fill)), fill=0; end
if(nargin<5||isempty(bgrd)), bgrd=0; end
if(size(bbs,2)==4), bbs(:,5)=1; end
M=zeros(h,w); B=true(h,w); n=size(bbs,1);
if( fill==0 )
p=floor(getCenter(bbs)); p=sub2ind([h w],p(:,2),p(:,1));
for i=1:n, M(p(i))=M(p(i))+bbs(i,5); end
if(bgrd~=0), B(p)=0; end
else
bbs=[intersect(round(bbs),[1 1 w h]) bbs(:,5)]; n=size(bbs,1);
x0=bbs(:,1); x1=x0+bbs(:,3)-1; y0=bbs(:,2); y1=y0+bbs(:,4)-1;
for i=1:n, y=y0(i):y1(i); x=x0(i):x1(i);
M(y,x)=M(y,x)+bbs(i,5); B(y,x)=0; end
end
if(bgrd~=0), M(B)=bgrd; end
end
|
github
|
3arbouch/PersonDetection-master
|
imwrite2.m
|
.m
|
PersonDetection-master/Source/toolbox/images/imwrite2.m
| 5,086 |
utf_8
|
c98d66c2cddd9ec90beb9b1bbde31fe0
|
function I = imwrite2( I, mulFlag, imagei, path, ...
name, ext, nDigits, nSplits, spliti, varargin )
% Similar to imwrite, except follows a strict naming convention.
%
% Wrapper for imwrite that writes file to the filename:
% fName = [path name int2str2(i,nDigits) '.' ext];
% Using imwrite:
% imwrite( I, fName, writePrms )
% If I represents a stack of images, the ith image is written to:
% fNamei = [path name int2str2(i+imagei-1,nDigits) '.' ext];
% If I=[], then imwrite2 will attempt to read images from disk instead.
% If dir spec. by 'path' does not exist, imwrite2 attempts to create it.
%
% mulFlag controls how I is interpreted. If mulFlag==0, then I is
% intrepreted as a single image, otherwise I is interpreted as a stack of
% images, where I(:,:,...,j) represents the jth image (see fevalArrays for
% more info).
%
% If nSplits>1, writes/reads images into/from multiple directories. This is
% useful since certain OS handle very large directories (of say >20K
% images) rather poorly (I'm talking to you Bill). Thus, can take 100K
% images, and write into 5 separate dirs, then read them back in.
%
% USAGE
% I = imwrite2( I, mulFlag, imagei, path, ...
% [name], [ext], [nDigits], [nSplits], [spliti], [varargin] )
%
% INPUTS
% I - image or array or cell of images (if [] reads else writes)
% mulFlag - set to 1 if I represents a stack of images
% imagei - first image number
% path - directory where images are
% name - ['I'] base name of images
% ext - ['png'] extension of image
% nDigits - [5] number of digits for filename index
% nSplits - [1] number of dirs to break data into
% spliti - [0] first split (dir) number
% writePrms - [varargin] parameters to imwrite
%
% OUTPUTS
% I - image or images (read from disk if input I=[])
%
% EXAMPLE
% load images; I=images(:,:,1:10); clear IDXi IDXv t video videos images;
% imwrite2( I(:,:,1), 0, 0, 'rats/', 'rats', 'png', 5 ); % write 1
% imwrite2( I, 1, 0, 'rats/', 'rats', 'png', 5 ); % write 5
% I2 = imwrite2( [], 1, 0, 'rats/', 'rats', 'png', 5 ); % read 5
% I3 = fevalImages(@(x) x,{},'rats/','rats','png',0,4,5); % read 5
%
% EXAMPLE - multiple splits
% load images; I=images(:,:,1:10); clear IDXi IDXv t video videos images;
% imwrite2( I, 1, 0, 'rats', 'rats', 'png', 5, 2, 0 ); % write 10
% I2=imwrite2( [], 1, 0, 'rats', 'rats', 'png', 5, 2, 0 ); % read 10
%
% See also FEVALIMAGES, FEVALARRAYS
%
% Piotr's Computer Vision Matlab Toolbox Version 2.30
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<5 || isempty(name) ); name='I'; end;
if( nargin<6 || isempty(ext) ); ext='png'; end;
if( nargin<7 || isempty(nDigits) ); nDigits=5; end;
if( nargin<8 || isempty(nSplits) ); nSplits=1; end;
if( nargin<9 || isempty(spliti) ); spliti=0; end;
n = size(I,3); if(isempty(I)); n=0; end
% multiple splits -- call imwrite2 recursively
if( nSplits>1 )
write2inp = [ {name, ext, nDigits, 1, 0} varargin ];
if(n>0); nSplits=min(n,nSplits); end;
for s=1:nSplits
pathS = [path int2str2(s-1+spliti,2)];
if( n>0 ) % write
nPerDir = ceil( n / nSplits );
ISplit = I(:,:,1:min(end,nPerDir));
imwrite2( ISplit, nPerDir>1, 0, pathS, write2inp{:} );
if( s~=nSplits ); I = I(:,:,(nPerDir+1):end); end
else % read
ISplit = imwrite2( [], 1, 0, pathS, write2inp{:} );
I = cat(3,I,ISplit);
end
end
return;
end
% if I is empty read from disk
if( n==0 )
I = fevalImages( @(x) x, {}, path, name, ext, imagei, [], nDigits );
return;
end
% Check if path exists (create if not) and add '/' at end if needed
if( ~isempty(path) )
if(~exist(path,'dir'))
warning( ['creating directory: ' path] ); %#ok<WNTAG>
mkdir( path );
end;
if( path(end)~='\' && path(end)~='/' ); path(end+1) = '/'; end
end
% Write images using one of the two subfunctions
params = varargin;
if( mulFlag )
imwrite2m( [], 'init', imagei, path, name, ext, nDigits, params );
if( ~iscell(I) )
fevalArrays( I, @imwrite2m, 'write' );
else
fevalArrays( I, @(x) imwrite2m(x{1},'write') );
end
else
if( ~iscell(I) )
imwrite2s( I, imagei, path, name, ext, nDigits, params );
else
imwrite2s( I{1}, imagei, path, name, ext, nDigits, params );
end;
end
function varargout = imwrite2m( I, type, varargin )
% helper for writing multiple images (passed to fevalArrays)
persistent imagei path name ext nDigits params
switch type
case 'init'
narginchk(8,8);
[nstart, path, name, ext, nDigits, params] = deal(varargin{:});
if(isempty(nstart)); imagei=0; else imagei=nstart; end
varargout = {[]};
case 'write'
narginchk(2,2);
imwrite2s( I, imagei, path, name, ext, nDigits, params );
imagei = imagei+1;
varargout = {[]};
end
function imwrite2s( I, imagei, path, name, ext, nDigits, params )
% helper for writing a single image
fullname = [path name int2str2(imagei,nDigits) '.' ext];
imwrite( I, fullname, params{:} );
|
github
|
3arbouch/PersonDetection-master
|
convnFast.m
|
.m
|
PersonDetection-master/Source/toolbox/images/convnFast.m
| 9,102 |
utf_8
|
03d05e74bb7ae2ecb0afd0ac115fda39
|
function C = convnFast( A, B, shape )
% Fast convolution, replacement for both conv2 and convn.
%
% See conv2 or convn for more information on convolution in general.
%
% This works as a replacement for both conv2 and convn. Basically,
% performs convolution in either the frequency or spatial domain, depending
% on which it thinks will be faster (see below). In general, if A is much
% bigger then B then spatial convolution will be faster, but if B is of
% similar size to A and both are fairly big (such as in the case of
% correlation), convolution as multiplication in the frequency domain will
% tend to be faster.
%
% The shape flag can take on 1 additional value which is 'smooth'. This
% flag is intended for use with smoothing kernels. The returned matrix C
% is the same size as A with boundary effects handled in a special manner.
% That is instead of A being zero padded before being convolved with B;
% near the boundaries a cropped version of the matrix B is used, and the
% results is scaled by the fraction of the weight found in the cropped
% version of B. In this case each dimension of B must be odd, and all
% elements of B must be positive. There are other restrictions on when
% this flag can be used, and in general it is only useful for smoothing
% kernels. For 2D filtering it does not have much overhead, for 3D it has
% more and for higher dimensions much much more.
%
% For optimal performance some timing constants must be set to choose
% between doing convolution in the spatial and frequency domains, for more
% info see timeConv below.
%
% USAGE
% C = convnFast( A, B, [shape] )
%
% INPUTS
% A - d dimensional input matrix
% B - d dimensional matrix to convolve with A
% shape - ['full'] 'valid', 'full', 'same', or 'smooth'
%
% OUTPUTS
% C - result of convolution
%
% EXAMPLE
%
% See also CONV2, CONVN
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<3 || isempty(shape)); shape='full'; end
if( ~any(strcmp(shape,{'same', 'valid', 'full', 'smooth'})) )
error( 'convnFast: unknown shape flag' ); end
shapeorig = shape;
smoothFlag = (strcmp(shape,'smooth'));
if( smoothFlag ); shape = 'same'; end;
% get dimensions of A and B
ndA = ndims(A); ndB = ndims(B); nd = max(ndA,ndB);
sizA = size(A); sizB = size(B);
if (ndA>ndB); sizB = [sizB ones(1,ndA-ndB)]; end
if (ndA<ndB); sizA = [sizA ones(1,ndB-ndA)]; end
% ERROR CHECK if smoothflag
if( smoothFlag )
if( ~all( mod(sizB,2)==1 ) )
error('If flag==''smooth'' then must have odd sized mask');
end;
if( ~all( B>0 ) )
error('If flag==''smooth'' then mask must have >0 values.');
end;
if( any( (sizB-1)/2>sizA ) )
error('B is more then twice as big as A, cannot use flag==''smooth''');
end;
end
% OPTIMIZATION for 3D conv when B is actually 2D - calls (spatial) conv2
% repeatedly on 2D slices of A. Note that may need to rearange A and B
% first and use recursion. The benefits carry over to convnBound
% (which is faster for 2D arrays).
if( ndA==3 && ndB==3 && (sizB(1)==1 || sizB(2)==1) )
if (sizB(1)==1)
A = permute( A, [2 3 1]); B = permute( B, [2 3 1]);
C = convnFast( A, B, shapeorig );
C = permute( C, [3 1 2] );
elseif (sizB(2)==1)
A = permute( A, [3 1 2]); B = permute( B, [3 1 2]);
C = convnFast( A, B, shapeorig );
C = permute( C, [2 3 1] );
end
return;
elseif( ndA==3 && ndB==2 )
C1 = conv2( A(:,:,1), B, shape );
C = zeros( [size(C1), sizA(3)] ); C(:,:,1) = C1;
for i=2:sizA(3); C(:,:,i) = conv2( A(:,:,i), B, shape ); end
if (smoothFlag)
for i=1:sizA(3)
C(:,:,i) = convnBound(A(:,:,i),B,C(:,:,i),sizA(1:2),sizB(1:2));
end
end
return;
end
% get predicted time of convolution in frequency and spatial domain
% constants taken from timeConv
sizfft = 2.^ceil(real(log2(sizA+sizB-1))); psizfft=prod(sizfft);
frequenPt = 3 * 1e-7 * psizfft * log(psizfft);
if (nd==2)
spatialPt = 5e-9 * sizA(1) * sizA(2) * sizB(1) * sizB(2);
else
spatialPt = 5e-8 * prod(sizA) * prod(sizB);
end
% perform convolution
if ( spatialPt < frequenPt )
if (nd==2)
C = conv2( A, B, shape );
else
C = convn( A, B, shape );
end
else
C = convnFreq( A, B, sizA, sizB, shape );
end;
% now correct boundary effects (if shape=='smooth')
if( ~smoothFlag ); return; end;
C = convnBound( A, B, C, sizA, sizB );
function C = convnBound( A, B, C, sizA, sizB )
% calculate boundary values for C in spatial domain
nd = length(sizA);
radii = (sizB-1)/2;
% flip B appropriately (conv flips B)
for d=1:nd; B = flipdim(B,d); end
% accelerated case for 1D mask B
if( nd==2 && sizB(1)==1 )
sumB=sum(B(:)); r=radii(2); O=ones(1,sizA(1));
for i=1:r
Ai=A(:,1:r+i); Bi=B(r+2-i:end);
C(:,i)=sum(Ai.*Bi(O,:),2)/sum(Bi)*sumB;
Ai=A(:,end+1-r-i:end); Bi=B(1:(end-r+i-1));
C(:,end-i+1)=sum(Ai.*Bi(O,:),2)/sum(Bi)*sumB;
end; return;
elseif( nd==2 && sizB(2)==1 )
sumB=sum(B(:)); r=radii(1); O=ones(1,sizA(2));
for i=1:r
Ai=A(1:r+i,:); Bi=B(r+2-i:end);
C(i,:)=sum(Ai.*Bi(:,O),1)/sum(Bi)*sumB;
Ai=A(end+1-r-i:end,:); Bi=B(1:(end-r+i-1));
C(end-i+1,:)=sum(Ai.*Bi(:,O),1)/sum(Bi)*sumB;
end; return;
end
% get location that need to be updated
inds = {':'}; inds = inds(:,ones(1,nd));
Dind = zeros( sizA );
for d=1:nd
inds1 = inds; inds1{ d } = 1:radii(d);
inds2 = inds; inds2{ d } = sizA(d)-radii(d)+1:sizA(d);
Dind(inds1{:}) = 1; Dind(inds2{:}) = 1;
end
Dind = find( Dind );
Dndx = ind2sub2( sizA, Dind );
nlocs = length(Dind);
% get cuboid dimensions for all the boundary regions
sizeArep = repmat( sizA, [nlocs,1] );
radiiRep = repmat( radii, [nlocs,1] );
Astarts = max(1,Dndx-radiiRep);
Aends = min( sizeArep, Dndx+radiiRep);
Bstarts = Astarts + (1-Dndx+radiiRep);
Bends = Bstarts + (Aends-Astarts);
% now update these locations
vs = zeros( 1, nlocs );
if( nd==2 )
for i=1:nlocs % accelerated for 2D arrays
Apart = A( Astarts(i,1):Aends(i,1), Astarts(i,2):Aends(i,2) );
Bpart = B( Bstarts(i,1):Bends(i,1), Bstarts(i,2):Bends(i,2) );
v = (Apart.*Bpart); vs(i) = sum(v(:)) ./ sum(Bpart(:));
end
elseif( nd==3 ) % accelerated for 3D arrays
for i=1:nlocs
Apart = A( Astarts(i,1):Aends(i,1), Astarts(i,2):Aends(i,2), ...
Astarts(i,3):Aends(i,3) );
Bpart = B( Bstarts(i,1):Bends(i,1), Bstarts(i,2):Bends(i,2), ...
Bstarts(i,3):Bends(i,3) );
za = sum(sum(sum(Apart.*Bpart))); zb=sum(sum(sum(Bpart)));
vs(1,i) = za./zb;
end
else % general case [slow]
extract=cell(1,nd);
for i=1:nlocs
for d=1:nd; extract{d} = Astarts(i,d):Aends(i,d); end
Apart = A( extract{:} );
for d=1:nd; extract{d} = Bstarts(i,d):Bends(i,d); end
Bpart = B( extract{:} );
v = (Apart.*Bpart); vs(i) = sum(v(:)) ./ sum(Bpart(:));
end
end
C( Dind ) = vs * sum(B(:));
function C = convnFreq( A, B, sizA, sizB, shape )
% Convolution as multiplication in the frequency domain
siz = sizA + sizB - 1;
% calculate correlation in frequency domain
Fa = fftn(A,siz);
Fb = fftn(B,siz);
C = ifftn(Fa .* Fb);
% make sure output is real if inputs were both real
if(isreal(A) && isreal(B)); C = real(C); end
% crop to size
if(strcmp(shape,'valid'))
C = arrayToDims( C, max(0,sizA-sizB+1 ) );
elseif(strcmp(shape,'same'))
C = arrayToDims( C, sizA );
elseif(~strcmp(shape,'full'))
error('unknown shape');
end
function K = timeConv() %#ok<DEFNU>
% Function used to calculate constants for prediction of convolution in the
% frequency and spatial domains. Method taken from normxcorr2.m
% May need to reset K's if placing this on a new machine, however, their
% ratio should be about the same..
mintime = 4;
switch 3
case 1 % conv2 [[empirically K = 5e-9]]
% convolution time = K*prod(size(a))*prod(size(b))
siza = 30; sizb = 200;
a = ones(siza); b = ones(sizb);
t1 = cputime; t2 = t1; k = 0;
while (t2-t1)<mintime;
disc = conv2(a,b); k = k + 1; t2 = cputime; %#ok<NASGU>
end
K = (t2-t1)/k/siza^2/sizb^2;
case 2 % convn [[empirically K = 5e-8]]
% convolution time = K*prod(size(a))*prod(size(b))
siza = [10 10 10]; sizb = [30 30 10];
a = ones(siza); b = ones(sizb);
t1 = cputime; t2 = t1; k = 0;
while (t2-t1)<mintime;
disc = convn(a,b); k = k + 1; t2 = cputime; %#ok<NASGU>
end
K = (t2-t1)/k/prod(siza)/prod(sizb);
case 3 % fft (one dimensional) [[empirically K = 1e-7]]
% fft time = K * n log(n) [if n is power of 2]
% Works fastest for powers of 2. (so always zero pad until have
% size of power of 2?). 2 dimensional fft has to apply single
% dimensional fft to each column, and then signle dimensional fft
% to each resulting row. time = K * (mn)log(mn). Likewise for
% highter dimensions. convnFreq requires 3 such ffts.
n = 2^nextpow2(2^15);
vec = complex(rand(n,1),rand(n,1));
t1 = cputime; t2 = t1; k = 0;
while (t2-t1) < mintime;
disc = fft(vec); k = k + 1; t2 = cputime; %#ok<NASGU>
end
K = (t2-t1) / k / n / log(n);
end
|
github
|
3arbouch/PersonDetection-master
|
imMlGauss.m
|
.m
|
PersonDetection-master/Source/toolbox/images/imMlGauss.m
| 5,674 |
utf_8
|
56ead1b25fbe356f7912993d46468d02
|
function varargout = imMlGauss( G, symmFlag, show )
% Calculates max likelihood params of Gaussian that gave rise to image G.
%
% Suppose G contains an image of a gaussian distribution. One way to
% recover the parameters of the gaussian is to threshold the image, and
% then estimate the mean/covariance based on the coordinates of the
% thresholded points. A better method is to do no thresholding and instead
% use all the coordinates, weighted by their value. This function does the
% latter, except in a very efficient manner since all computations are done
% in parallel over the entire image.
%
% This function works over 2D or 3D images. It makes most sense when G in
% fact contains an image of a single gaussian, but a result will be
% returned regardless. All operations are performed on abs(G) in case it
% contains negative or complex values.
%
% symmFlag is an optional flag that if set to 1 then imMlGauss recovers
% the maximum likelihood symmetric gaussian. That is the variance in each
% direction is equal, and all covariance terms are 0. If symmFlag is set
% to 2 and G is 3D, imMlGauss recovers the ML guassian with equal
% variance in the 1st 2 dimensions (row and col) and all covariance terms
% equal to 0, but a possibly different variance in the 3rd (z or t)
% dimension.
%
% USAGE
% varargout = imMlGauss( G, [symmFlag], [show] )
%
% INPUTS
% G - image of a gaussian (weighted pixels)
% symmFlag - [0] see above
% show - [0] figure to use for optional display
%
% OUTPUTS
% mu - 2 or 3 element vector specifying the mean [row,col,z]
% C - 2x2 or 3x3 covariance matrix [row,col,z]
% GR - image of the recovered gaussian (faster if omitted)
% logl - log likelihood of G given recov. gaussian (faster if omitted)
%
% EXAMPLE - 2D
% R = rotationMatrix( pi/6 ); C=R'*[10^2 0; 0 20^2]*R;
% G = filterGauss( [200, 300], [150,100], C, 0 );
% [mu,C,GR,logl] = imMlGauss( G, 0, 1 );
% mask = maskEllipse( size(G,1), size(G,2), mu, C );
% figure(2); im(mask)
%
% EXAMPLE - 3D
% R = rotationMatrix( [1,1,0], pi/4 );
% C = R'*[5^2 0 0; 0 2^2 0; 0 0 4^2]*R;
% G = filterGauss( [50,50,50], [25,25,25], C, 0 );
% [mu,C,GR,logl] = imMlGauss( G, 0, 1 );
%
% See also GAUSS2ELLIPSE, PLOTGAUSSELLIPSES, MASKELLIPSE
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<2 || isempty(symmFlag) ); symmFlag=0; end;
if( nargin<3 || isempty(show) ); show=0; end;
varargout = cell(1,max(nargout,2));
nd = ndims(G); G = abs(G);
if( nd==2 )
[varargout{:}] = imMlGauss2D( G, symmFlag, show );
elseif( nd==3 )
[varargout{:}] = imMlGauss3D( G, symmFlag, show );
else
error( 'Unsupported dimension for G. G must be 2D or 3D.' );
end
function [mu,C,GR,logl] = imMlGauss2D( G, symmFlag, show )
% to be used throughout calculations
[ gridCols, gridRows ] = meshgrid( 1:size(G,2), 1:size(G,1) );
sumG = sum(G(:)); if(sumG==0); sumG=1; end;
% recover mean
muCol = (gridCols .* G); muCol = sum( muCol(:) ) / sumG;
muRow = (gridRows .* G); muRow = sum( muRow(:) ) / sumG;
mu = [muRow, muCol];
% recover sigma
distCols = (gridCols - muCol);
distRows = (gridRows - muRow);
if( symmFlag==0 )
Ccc = (distCols .^ 2) .* G; Ccc = sum(Ccc(:)) / sumG;
Crr = (distRows .^ 2) .* G; Crr = sum(Crr(:)) / sumG;
Crc = (distCols .* distRows) .* G; Crc = sum(Crc(:)) / sumG;
C = [Crr Crc; Crc Ccc];
elseif( symmFlag==1 )
sigSq = (distCols.^2 + distRows.^2) .* G;
sigSq = 1/2 * sum(sigSq(:)) / sumG;
C = sigSq*eye(2);
else
error(['Illegal value for symmFlag: ' num2str(symmFlag)]);
end
% get the log likelihood of the data
if (nargout>2)
GR = filterGauss( size(G), mu, C );
probs = GR; probs( probs<realmin ) = realmin;
logl = G .* log( probs );
logl = sum( logl(:) );
end
% plot ellipses
if (show)
figure(show); im(G);
hold('on'); plotGaussEllipses( mu, C, 2 ); hold('off');
end
function [mu,C,GR,logl] = imMlGauss3D( G, symmFlag, show )
% to be used throughout calculations
[gridCols,gridRows,gridZs]=meshgrid(1:size(G,2),1:size(G,1),1:size(G,3));
sumG = sum(G(:));
% recover mean
muCol = (gridCols .* G); muCol = sum( muCol(:) ) / sumG;
muRow = (gridRows .* G); muRow = sum( muRow(:) ) / sumG;
muZ = (gridZs .* G); muZ = sum( muZ(:) ) / sumG;
mu = [muRow, muCol, muZ];
% recover C
distCols = (gridCols - muCol);
distRows = (gridRows - muRow);
distZs = (gridZs - muZ);
if( symmFlag==0 )
distColsG = distCols .* G; distRowsG = distRows .* G;
Ccc = distCols .* distColsG; Ccc = sum(Ccc(:));
Crc = distRows .* distColsG; Crc = sum(Crc(:));
Czc = distZs .* distColsG; Czc = sum(Czc(:));
Crr = distRows .* distRowsG; Crr = sum(Crr(:));
Czr = distZs .* distRowsG; Czr = sum(Czr(:));
Czz = distZs .* distZs .* G; Czz = sum(Czz(:));
C = [Crr Crc Czr; Crc Ccc Czc; Czr Czc Czz] / sumG;
elseif( symmFlag==1 )
sigSq = (distCols.^2 + distRows.^2 + distZs .^ 2) .* G;
sigSq = 1/3 * sum(sigSq(:));
C = [sigSq 0 0; 0 sigSq 0; 0 0 sigSq] / sumG;
elseif( symmFlag==2 )
sigSq = (distCols.^2 + distRows.^2) .* G; sigSq = 1/2 * sum(sigSq(:));
tauSq = (distZs .^ 2) .* G; tauSq = sum(tauSq(:));
C = [sigSq 0 0; 0 sigSq 0; 0 0 tauSq] / sumG;
else
error(['Illegal value for symmFlag: ' num2str(symmFlag)])
end
% get the log likelihood of the data
if( nargout>2 || (show) )
GR = filterGauss( size(G), mu, C );
probs = GR; probs( probs<realmin ) = realmin;
logl = G .* log( probs );
logl = sum( logl(:) );
end
% plot G and GR
if( show )
figure(show); montage2(G);
figure(show+1); montage2(GR);
end
|
github
|
3arbouch/PersonDetection-master
|
montage2.m
|
.m
|
PersonDetection-master/Source/toolbox/images/montage2.m
| 7,484 |
utf_8
|
828f57d7b1f67d36eeb6056f06568ebf
|
function varargout = montage2( IS, prm )
% Used to display collections of images and videos.
%
% Improved version of montage, with more control over display.
% NOTE: Can convert between MxNxT and MxNx3xT image stack via:
% I = repmat( I, [1,1,1,3] ); I = permute(I, [1,2,4,3] );
%
% USAGE
% varargout = montage2( IS, [prm] )
%
% INPUTS
% IS - MxNxTxR or MxNxCxTxR, where C==1 or C==3, and R may be 1
% or cell vector of MxNxT or MxNxCxT matrices
% prm
% .showLines - [1] whether to show lines separating the various frames
% .extraInfo - [0] if 1 then a colorbar is shown as well as impixelinfo
% .cLim - [] cLim = [clow chigh] optional scaling of data
% .mm - [] #images/col per montage
% .nn - [] #images/row per montage
% .labels - [] cell array of labels (strings) (T if R==1 else R)
% .perRow - [0] only if R>1 and not cell, alternative displays method
% .hasChn - [0] if true assumes IS is MxNxCxTxR else MxNxTxR
% .padAmt - [0] only if perRow, amount to pad when in row mode
% .padEl - [] pad element, defaults to min value in IS
%
% OUTPUTS
% h - image handle
% m - #images/col
% nn - #images/row
%
% EXAMPLE - [3D] show a montage of images
% load( 'images.mat' ); clf; montage2( images );
%
% EXAMPLE - [3D] show a montage of images with labels
% load( 'images.mat' );
% for i=1:50; labels{i}=['I-' int2str2(i,2)]; end
% prm = struct('extraInfo',1,'perRow',0,'labels',{labels});
% clf; montage2( images(:,:,1:50), prm );
%
% EXAMPLE - [3D] show a montage of images with color boundaries
% load( 'images.mat' );
% I3 = repmat(permute(images,[1 2 4 3]),[1,1,3,1]); % add color chnls
% prm = struct('padAmt',4,'padEl',[50 180 50],'hasChn',1,'showLines',0);
% clf; montage2( I3(:,:,:,1:48), prm )
%
% EXAMPLE - [4D] show a montage of several groups of images
% for i=1:25; labels{i}=['V-' int2str2(i,2)]; end
% prm = struct('labels',{labels});
% load( 'images.mat' ); clf; montage2( videos(:,:,:,1:25), prm );
%
% EXAMPLE - [4D] show using 'row' format
% load( 'images.mat' );
% prm = struct('perRow',1, 'padAmt',6, 'padEl',255 );
% figure(1); clf; montage2( videos(:,:,:,1:10), prm );
%
% See also MONTAGE, PLAYMOVIE, FILMSTRIP
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<2 ); prm=struct(); end
varargout = cell(1,nargout);
%%% get parameters (set defaults)
dfs = {'showLines',1, 'extraInfo',0, 'cLim',[], 'mm',[], 'nn',[],...
'labels',[], 'perRow',false, 'padAmt',0, 'padEl',[], 'hasChn',false };
prm = getPrmDflt( prm, dfs );
extraInfo=prm.extraInfo; labels=prm.labels; perRow=prm.perRow;
hasChn=prm.hasChn;
%%% If IS is not a cell convert to MxNxCxTxR array
if( iscell(IS) && numel(IS)==1 ); IS=IS{1}; end;
if( ~iscell(IS) && ~ismatrix(IS) )
siz=size(IS);
if( ~hasChn );
IS=reshape(IS,[siz(1:2),1,siz(3:end)]);
prm.hasChn = true;
end;
if(ndims(IS)>5); error('montage2: input too large'); end;
end
if( ~iscell(IS) && size(IS,5)==1 ) %%% special case call subMontage once
[varargout{:}] = subMontage(IS,prm);
title(inputname(1));
elseif( perRow ) %%% display each montage in row format
if(iscell(IS)); error('montage2: IS cannot be a cell if perRow'); end;
siz = size(IS);
IS=reshape(permute(IS,[1 2 4 3 5]),siz(1),[],siz(3),siz(5));
if( nargout ); varargout{1}=IS; end
prm.perRow = false; prm.hasChn=true;
[varargout{2:end}] = subMontage( IS, prm );
title(inputname(1));
else %%% display each montage using subMontage
% convert to cell array
if( iscell(IS) )
nMontages = numel(IS);
else
nMontages = size(IS,5);
IS = squeeze(mat2cell2( IS, [1 1 1 1 nMontages] ));
end
% draw each montage
clf;
nn = ceil( sqrt(nMontages) ); mm = ceil(nMontages/nn);
for i=1:nMontages
subplot(mm,nn,i);
prmSub=prm; prmSub.extraInfo=0; prmSub.labels=[];
if( ~isempty(IS{i}) )
subMontage( IS{i}, prmSub );
else
set(gca,'XTick',[]); set(gca,'YTick',[]);
end
if(~isempty(labels)); title(labels{i}); end
end
if( extraInfo ); impixelinfo; end;
end
function varargout = subMontage( IS, prm )
% this function is a generalized version of Matlab's montage.m
% get parameters (set defaults)
dfs = {'showLines',1, 'extraInfo',0, 'cLim',[], 'mm',[], 'nn',[], ...
'labels',[], 'perRow',false, 'hasChn',false, 'padAmt',0, 'padEl',[] };
prm = getPrmDflt( prm, dfs );
showLines=prm.showLines; extraInfo=prm.extraInfo; cLim=prm.cLim;
mm=prm.mm; nn=prm.nn; labels=prm.labels; hasChn=prm.hasChn;
padAmt=prm.padAmt; padEl=prm.padEl;
if( prm.perRow ); mm=1; end;
% get/test image format info and parameters
if( hasChn )
if( ndims(IS)>4 || ~any(size(IS,3)==[1 3]) )
error('montage2: unsupported dimension of IS'); end
else
if( ndims(IS)>3 );
error('montage2: unsupported dimension of IS'); end
IS = permute(IS, [1 2 4 3] );
end
siz = size(IS); nCh=size(IS,3); nIm = size(IS,4); sizPad=siz+padAmt;
if( ~isempty(labels) && nIm~=length(labels) )
error('montage2: incorrect number of labels');
end
% set up the padEl correctly (must have same type / nCh as IS)
if(isempty(padEl))
if(isempty(cLim)); padEl=min(IS(:)); else padEl=cLim(1); end; end
if(length(padEl)==1); padEl=repmat(padEl,[1 nCh]); end;
if(length(padEl)~=nCh); error( 'invalid padEl' ); end;
padEl = feval( class(IS), padEl );
padEl = reshape( padEl, 1, 1, [] );
padAmt = floor(padAmt/2 + .5)*2;
% get layout of images (mm=#images/row, nn=#images/col)
if( isempty(mm) || isempty(nn))
if( isempty(mm) && isempty(nn))
nn = min( ceil(sqrt(sizPad(1)*nIm/sizPad(2))), nIm );
mm = ceil( nIm/nn );
elseif( isempty(mm) )
nn = min( nn, nIm );
mm = ceil(nIm/nn);
else
mm = min( mm, nIm );
nn = ceil(nIm/mm);
end
% often can shrink dimension further
while((mm-1)*nn>=nIm); mm=mm-1; end;
while((nn-1)*mm>=nIm); nn=nn-1; end;
end
% Calculate I (M*mm x N*nn size image)
I = repmat(padEl, [mm*sizPad(1), nn*sizPad(2), 1]);
rows = 1:siz(1); cols = 1:siz(2);
for k=1:nIm
rowsK = rows + floor((k-1)/nn)*sizPad(1)+padAmt/2;
colsK = cols + mod(k-1,nn)*sizPad(2)+padAmt/2;
I(rowsK,colsK,:) = IS(:,:,:,k);
end
% display I
if( ~isempty(cLim)); h=imagesc(I,cLim); else h=imagesc(I); end
colormap(gray); axis('image');
if( extraInfo )
colorbar; impixelinfo;
else
set(gca,'Visible','off')
end
% draw lines separating frames
if( showLines )
montageWd = nn * sizPad(2) + .5;
montageHt = mm * sizPad(1) + .5;
for i=1:mm-1
ht = i*sizPad(1) +.5; line([.5,montageWd],[ht,ht]);
end
for i=1:nn-1
wd = i*sizPad(2) +.5; line([wd,wd],[.5,montageHt]);
end
end
% plot text labels
textalign = { 'VerticalAlignment','bottom','HorizontalAlignment','left'};
if( ~isempty(labels) )
count=1;
for i=1:mm;
for j=1:nn
if( count<=nIm )
rStr = i*sizPad(1)-padAmt/2;
cStr =(j-1+.1)*sizPad(2)+padAmt/2;
text(cStr,rStr,labels{count},'color','r',textalign{:});
count = count+1;
end
end
end
end
% cross out unused frames
[nns,mms] = ind2sub( [nn,mm], nIm+1 );
for i=mms-1:mm-1
for j=nns-1:nn-1,
rStr = i*sizPad(1)+.5+padAmt/2; rs = [rStr,rStr+siz(1)];
cStr = j*sizPad(2)+.5+padAmt/2; cs = [cStr,cStr+siz(2)];
line( cs, rs ); line( fliplr(cs), rs );
end
end
% optional output
if( nargout>0 ); varargout={h,mm,nn}; end
|
github
|
3arbouch/PersonDetection-master
|
jitterImage.m
|
.m
|
PersonDetection-master/Source/toolbox/images/jitterImage.m
| 5,252 |
utf_8
|
3310f8412af00fd504c6f94b8c48992c
|
function IJ = jitterImage( I, varargin )
% Creates multiple, slightly jittered versions of an image.
%
% Takes an image I, and generates a number of images that are copies of the
% original image with slight translation, rotation and scaling applied. If
% the input image is actually an MxNxK stack of images then applies op to
% each image. Rotations and translations are specified by giving a range
% and a max value for each. For example, if mPhi=10 and nPhi=5, then the
% actual rotations applied are linspace(-mPhi,mPhi,nPhi)=[-10 -5 0 5 10].
% Likewise if mTrn=3 and nTrn=3 then the translations are [-3 0 3]. Each
% tran is applied in the x direction as well as the y direction. Each
% combination of rotation, tran in x, tran in y and scale is used (for
% example phi=5, transx=-3, transy=0), so the total number of images
% generated is R=nTrn*nTrn*nPhi*nScl. Finally, jsiz controls the size of
% the cropped images. If jsiz gives a size that's sufficiently smaller than
% I then all data in the the final set will come from I. Otherwise, I must
% be padded first (by calling padarray with the 'replicate' option).
%
% USAGE
% function IJ = jitterImage( I, varargin )
%
% INPUTS
% I - image (MxN) or set of K images (MxNxK)
% varargin - additional params (struct or name/value pairs)
% .maxn - [inf] maximum jitters to generate (prior to flip)
% .nPhi - [0] number of rotations
% .mPhi - [0] max value for rotation
% .nTrn - [0] number of translations
% .mTrn - [0] max value for translation
% .flip - [0] if true then also adds reflection of each image
% .jsiz - [] Final size of each image in IJ
% .scls - [1 1] nScl x 2 array of vert/horiz scalings
% .method - ['linear'] interpolation method for imtransform2
% .hasChn - [0] if true I is MxNxC or MxNxCxK
%
% OUTPUTS
% IJ - MxNxKxR or MxNxCxKxR set of images, R=(nTrn^2*nPhi*nScl)
%
% EXAMPLE
% load trees; I=imresize(ind2gray(X,map),[41 41]); clear X caption map
% % creates 10 (of 7^2*2) images of slight trans
% IJ = jitterImage(I,'nTrn',7,'mTrn',3,'maxn',10); montage2(IJ)
% % creates 5 images of slight rotations w reflection
% IJ = jitterImage(I,'nPhi',5,'mPhi',25,'flip',1); montage2(IJ)
% % creates 45 images of both rot and slight trans
% IJ = jitterImage(I,'nPhi',5,'mPhi',10,'nTrn',3,'mTrn',2); montage2(IJ)
% % additionally create multiple scaled versions
% IJ = jitterImage(I,'scls',[1 1; 2 1; 1 2; 2 2]); montage2(IJ)
% % example on color image (5 images of slight rotations)
% I=imResample(imread('peppers.png'),[100,100]);
% IJ=jitterImage(I,'nPhi',5,'mPhi',25,'hasChn',1);
% montage2(uint8(IJ),{'hasChn',1})
%
% See also imtransform2
%
% Piotr's Computer Vision Matlab Toolbox Version 2.65
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get additional parameters
siz=size(I);
dfs={'maxn',inf, 'nPhi',0, 'mPhi',0, 'nTrn',0, 'mTrn',0, 'flip',0, ...
'jsiz',siz(1:2), 'scls',[1 1], 'method','linear', 'hasChn',0};
[maxn,nPhi,mPhi,nTrn,mTrn,flip,jsiz,scls,method,hasChn] = ...
getPrmDflt(varargin,dfs,1);
if(nPhi<1), mPhi=0; nPhi=1; end; if(nTrn<1), mTrn=0; nTrn=1; end
% I must be big enough to support given ops so grow I if necessary
trn=linspace(-mTrn,mTrn,nTrn); [dX,dY]=meshgrid(trn,trn);
dY=dY(:)'; dX=dX(:)'; phis=linspace(-mPhi,mPhi,nPhi)/180*pi;
siz1=jsiz+2*max(dX); if(nPhi>1), siz1=sqrt(2)*siz1+1; end
siz1=[siz1(1)*max(scls(:,1)) siz1(2)*max(scls(:,2))];
pad=(siz1-siz(1:2))/2; pad=max([ceil(pad) 0],0);
if(any(pad>0)), I=padarray(I,pad,'replicate','both'); end
% jitter each image
nScl=size(scls,1); nTrn=length(dX); nPhi=length(phis);
nOps=min(maxn,nTrn*nPhi*nScl); if(flip), nOps=nOps*2; end
if(hasChn), nd=3; jsiz=[jsiz siz(3)]; else nd=2; end
n=size(I,nd+1); IJ=zeros([jsiz nOps n],class(I));
is=repmat({':'},1,nd); prm={method,maxn,jsiz,phis,dX,dY,scls,flip};
for i=1:n, IJ(is{:},:,i)=jitterImage1(I(is{:},i),prm{:}); end
end
function IJ = jitterImage1( I,method,maxn,jsiz,phis,dX,dY,scls,flip )
% generate list of transformations (HS)
nScl=size(scls,1); nTrn=length(dX); nPhi=length(phis);
nOps=nTrn*nPhi*nScl; HS=zeros(3,3,nOps); k=0;
for s=1:nScl, S=[scls(s,1) 0; 0 scls(s,2)];
for p=1:nPhi, R=rotationMatrix(phis(p));
for t=1:nTrn, k=k+1; HS(:,:,k)=[S*R [dX(t); dY(t)]; 0 0 1]; end
end
end
% apply each transformation HS(:,:,i) to image I
if(nOps>maxn), HS=HS(:,:,randSample(nOps,maxn)); nOps=maxn; end
siz=size(I); nd=ndims(I); nCh=size(I,3);
I1=I; p=(siz-jsiz)/2; IJ=zeros([jsiz nOps],class(I));
for i=1:nOps, H=HS(:,:,i); d=H(1:2,3)';
if( all(all(H(1:2,1:2)==eye(2))) && all(mod(d,1)==0) )
% handle transformation that's just an integer translation
s=max(1-d,1); e=min(siz(1:2)-d,siz(1:2)); s1=2-min(1-d,1); e1=e-s+s1;
I1(s1(1):e1(1),s1(2):e1(2),:) = I(s(1):e(1),s(2):e(2),:);
else % handle general transformations
for j=1:nCh, I1(:,:,j)=imtransform2(I(:,:,j),H,'method',method); end
end
% crop and store result
I2 = I1(p(1)+1:end-p(1),p(2)+1:end-p(2),:);
if(nd==2), IJ(:,:,i)=I2; else IJ(:,:,:,i)=I2; end
end
% finally flip each resulting image
if(flip), IJ=cat(nd+1,IJ,IJ(:,end:-1:1,:,:)); end
end
|
github
|
3arbouch/PersonDetection-master
|
movieToImages.m
|
.m
|
PersonDetection-master/Source/toolbox/images/movieToImages.m
| 889 |
utf_8
|
28c71798642af276951ee27e2d332540
|
function I = movieToImages( M )
% Creates a stack of images from a matlab movie M.
%
% Repeatedly calls frame2im. Useful for playback with playMovie.
%
% USAGE
% I = movieToImages( M )
%
% INPUTS
% M - a matlab movie
%
% OUTPUTS
% I - MxNxT array (of images)
%
% EXAMPLE
% load( 'images.mat' ); [X,map]=gray2ind(video(:,:,1));
% M = fevalArrays( video, @(x) im2frame(gray2ind(x),map) );
% I = movieToImages(M); playMovie(I);
%
% See also PLAYMOVIE
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
I = fevalArrays( M, @frame2Ii );
function I = frame2Ii( F )
[I,map] = frame2im( F );
if( isempty(map) )
if( size(I,3)==3 )
classname = class( I );
I = sum(I,3)/3;
I = feval( classname, I );
end
else
I = ind2gray( I, map );
end
|
github
|
3arbouch/PersonDetection-master
|
toolboxUpdateHeader.m
|
.m
|
PersonDetection-master/Source/toolbox/external/toolboxUpdateHeader.m
| 2,255 |
utf_8
|
7a5b75e586be48da97c84d20b59887ff
|
function toolboxUpdateHeader
% Update the headers of all the files.
%
% USAGE
% toolboxUpdateHeader
%
% INPUTS
%
% OUTPUTS
%
% EXAMPLE
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.40
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
header={
'Piotr''s Computer Vision Matlab Toolbox Version 3.40'; ...
'Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]'; ...
'Licensed under the Simplified BSD License [see external/bsd.txt]'};
root=fileparts(fileparts(mfilename('fullpath')));
ds=dir(root); ds=ds([ds.isdir]); ds={ds.name};
ds=ds(3:end); ds=setdiff(ds,{'.git','doc'});
subds = { '/', '/private/' };
exts = {'m','c','cpp','h','hpp'};
omit = {'Contents.m','fibheap.h','fibheap.cpp'};
for i=1:length(ds)
for j=1:length(subds)
for k=1:length(exts)
d=[root '/' ds{i} subds{j}];
if(k==1), comment='%'; else comment='*'; end
fs=dir([d '*.' exts{k}]); fs={fs.name}; fs=setdiff(fs,omit);
n=length(fs); for f=1:n, fs{f}=[d fs{f}]; end
for f=1:n, toolboxUpdateHeader1(fs{f},header,comment); end
end
end
end
end
function toolboxUpdateHeader1( fName, header, comment )
% set appropriate comment symbol in header
m=length(header); for i=1:m, header{i}=[comment ' ' header{i}]; end
% read in file and find header
disp(fName); lines=readFile(fName);
loc = find(not(cellfun('isempty',strfind(lines,header{1}(1:40)))));
if(isempty(loc)), error('NO HEADER: %s\n',fName); end; loc=loc(1);
% check that header is properly formed, return if up to date
for i=1:m; assert(isequal(lines{loc+i-1}(1:10),header{i}(1:10))); end
if(~any(strfind(lines{loc},'NEW'))); return; end
% update copyright year and overwrite rest of header
lines{loc+1}(13:16)=header{2}(13:16);
for i=[1 3:m]; lines{loc+i-1}=header{i}; end
writeFile( fName, lines );
end
function lines = readFile( fName )
fid = fopen( fName, 'rt' ); assert(fid~=-1);
lines=cell(10000,1); n=0;
while( 1 )
n=n+1; lines{n}=fgetl(fid);
if( ~ischar(lines{n}) ), break; end
end
fclose(fid); n=n-1; lines=lines(1:n);
end
function writeFile( fName, lines )
fid = fopen( fName, 'w' );
for i=1:length(lines); fprintf( fid, '%s\n', lines{i} ); end
fclose(fid);
end
|
github
|
3arbouch/PersonDetection-master
|
toolboxGenDoc.m
|
.m
|
PersonDetection-master/Source/toolbox/external/toolboxGenDoc.m
| 3,639 |
utf_8
|
4c21fb34fa9b6002a1a98a28ab40c270
|
function toolboxGenDoc
% Generate documentation, must run from dir toolbox.
%
% 1) Make sure to update and run toolboxUpdateHeader.m
% 2) Update history.txt appropriately, including w current version
% 3) Update overview.html file with the version/date/link to zip:
% edit external/m2html/templates/frame-piotr/overview.html
%
% USAGE
% toolboxGenDoc
%
% INPUTS
%
% OUTPUTS
%
% EXAMPLE
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.40
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% Requires external/m2html to be in path.
cd(fileparts(mfilename('fullpath'))); cd('../');
addpath([pwd '/external/m2html']);
% delete temporary files that should not be part of release
fs={'pngreadc','pngwritec','rjpg8c','wjpg8c','png'};
for i=1:length(fs), delete(['videos/private/' fs{i} '.*']); end
delete('detector/models/*Dets.txt');
% delete old doc and run m2html
if(exist('doc/','dir')), rmdir('doc/','s'); end
dirs={'channels','classify','detector',...
'images','filters','matlab','videos'};
m2html('mfiles',dirs,'htmldir','doc','recursive','on','source','off',...
'template','frame-piotr','index','menu','global','on');
% copy custom menu.html and history file
sDir='external/m2html/templates/';
copyfile([sDir 'menu-for-frame-piotr.html'],'doc/menu.html');
copyfile('external/history.txt','doc/history.txt');
% remove links to private/ in the menu.html files and remove private/ dirs
for i=1:length(dirs)
name = ['doc/' dirs{i} '/menu.html'];
fid=fopen(name,'r'); c=fread(fid,'*char')'; fclose(fid);
c=regexprep(c,'<li>([^<]*[<]?[^<]*)private([^<]*[<]?[^<]*)</li>','');
fid=fopen(name,'w'); fwrite(fid,c); fclose(fid);
name = ['doc/' dirs{i} '/private/'];
if(exist(name,'dir')), rmdir(name,'s'); end
end
% postprocess each html file
for d=1:length(dirs)
fs=dir(['doc/' dirs{d} '/*.html']); fs={fs.name};
for j=1:length(fs), postProcess(['doc/' dirs{d} '/' fs{j}]); end
end
end
function postProcess( fName )
lines=readFile(fName);
assert(strcmp(lines{end-1},'</body>') && strcmp(lines{end},'</html>'));
% remove m2html datestamp (if present)
assert(strcmp(lines{end-2}(1:22),'<hr><address>Generated'));
if( strcmp(lines{end-2}(1:25),'<hr><address>Generated on'))
lines{end-2}=regexprep(lines{end-2}, ...
'<hr><address>Generated on .* by','<hr><address>Generated by');
end
% remove crossreference information
is=find(strcmp('<!-- crossreference -->',lines));
if(~isempty(is)), assert(length(is)==2); lines(is(1):is(2))=[]; end
% insert Google Analytics snippet to end of file
ga={ '';
'<!-- Start of Google Analytics Code -->';
'<script type="text/javascript">';
'var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");';
'document.write(unescape("%3Cscript src=''" + gaJsHost + "google-analytics.com/ga.js'' type=''text/javascript''%3E%3C/script%3E"));';
'</script>';
'<script type="text/javascript">';
'var pageTracker = _gat._getTracker("UA-4884268-1");';
'pageTracker._initData();';
'pageTracker._trackPageview();';
'</script>';
'<!-- end of Google Analytics Code -->';
'' };
lines = [lines(1:end-3); ga; lines(end-2:end)];
% write file
writeFile( fName, lines );
end
function lines = readFile( fName )
fid = fopen( fName, 'rt' ); assert(fid~=-1);
lines=cell(10000,1); n=0;
while( 1 )
n=n+1; lines{n}=fgetl(fid);
if( ~ischar(lines{n}) ), break; end
end
fclose(fid); n=n-1; lines=lines(1:n);
end
function writeFile( fName, lines )
fid = fopen( fName, 'w' );
for i=1:length(lines); fprintf( fid, '%s\r\n', lines{i} ); end
fclose(fid);
end
|
github
|
3arbouch/PersonDetection-master
|
toolboxHeader.m
|
.m
|
PersonDetection-master/Source/toolbox/external/toolboxHeader.m
| 2,391 |
utf_8
|
30c24a94fb54ca82622719adcab17903
|
function [y1,y2] = toolboxHeader( x1, x2, x3, prm )
% One line description of function (will appear in file summary).
%
% General commments explaining purpose of function [width is 75
% characters]. There may be multiple paragraphs. In special cases some or
% all of these guidelines may need to be broken.
%
% Next come a series of sections, including USAGE, INPUTS, OUTPUTS,
% EXAMPLE, and "See also". Each of these fields should always appear, even
% if nothing follows (for example no inputs). USAGE should usually be a
% copy of the first line of code (which begins with "function"), minus the
% word "function". Optional parameters are surrounded by brackets.
% Occasionally, there may be more than 1 distinct usage, in this case list
% additional usages. In general try to avoid this. INPUTS/OUTPUTS are
% self explanatory, however if there are multiple usages can be subdivided
% as below. EXAMPLE should list 1 or more useful examples. Main comment
% should all appear as one contiguous block. Next a blank comment line,
% and then a short comment that includes the toolbox version.
%
% USAGE
% xsum = toolboxHeader( x1, x2, [x3], [prm] )
% [xprod, xdiff] = toolboxHeader( x1, x2, [x3], [prm] )
%
% INPUTS
% x1 - descr. of variable 1,
% x2 - descr. of variable 2, keep spacing like this
% if descr. spans multiple lines do this
% x3 - [0] indicates an optional variable, put def val in []
% prm - [] param struct
% .p1 parameter 1 descr
% .p2 parameter 2 descr
%
% OUTPUTS - and whatever after the dash
% xsum - sum of xs
%
% OUTPUTS - usage 2
% xprod - prod of xs
% xdiff - negative sum of xs
%
% EXAMPLE - and whatever after the dash
% y = toolboxHeader( 1, 2 );
%
% EXAMPLE - example 2
% y = toolboxHeader( 2, 3 );
%
% See also GETPRMDFLT
%
% Piotr's Computer Vision Matlab Toolbox Version 2.10
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% optional arguments x3 and prm
if( nargin<3 || isempty(x3) ), x3=0; end
if( nargin<4 || isempty(prm) ), prm=[]; end %#ok<NASGU>
% indents should be set with Matlab's "smart indent" (with 2 spaces)
if( nargout==1 )
y1 = add(x1,x2) + x3;
else
y1 = x1 * x2 * x3;
y2 = - x1 - x2 - x3;
end
function s=add(x,y)
% optional sub function comment
s=x+y;
|
github
|
3arbouch/PersonDetection-master
|
mdot.m
|
.m
|
PersonDetection-master/Source/toolbox/external/m2html/mdot.m
| 2,516 |
utf_8
|
34a14428c433e118d1810e23f5a6caf5
|
function mdot(mmat, dotfile,f)
%MDOT - Export a dependency graph into DOT language
% MDOT(MMAT, DOTFILE) loads a .mat file generated by M2HTML using option
% ('save','on') and writes an ascii file using the DOT language that can
% be drawn using <dot> or <neato> .
% MDOT(MMAT, DOTFILE,F) builds the graph containing M-file F and its
% neighbors only.
% See the following page for more details:
% <http://www.graphviz.org/>
%
% Example:
% mdot('m2html.mat','m2html.dot');
% !dot -Tps m2html.dot -o m2html.ps
% !neato -Tps m2html.dot -o m2html.ps
%
% See also M2HTML
% Copyright (C) 2004 Guillaume Flandin <[email protected]>
% $Revision: 1.1 $Date: 2004/05/05 17:14:09 $
error(nargchk(2,3,nargin));
if ischar(mmat)
load(mmat);
elseif iscell(mmat)
hrefs = mmat{1};
names = mmat{2};
options = mmat{3};
if nargin == 3, mfiles = mmat{4}; end
mdirs = cell(size(names));
[mdirs{:}] = deal('');
if nargin == 2 & length(mmat) > 3,
mdirs = mmat{4};
end;
else
error('[mdot] Invalid argument: mmat.');
end
fid = fopen(dotfile,'wt');
if fid == -1, error(sprintf('[mdot] Cannot open %s.',dotfile)); end
fprintf(fid,'/* Created by mdot for Matlab */\n');
fprintf(fid,'digraph m2html {\n');
% if 'names' contains '.' then they should be surrounded by '"'
if nargin == 2
for i=1:size(hrefs,1)
n = find(hrefs(i,:) == 1);
m{i} = n;
for j=1:length(n)
fprintf(fid,[' ' names{i} ' -> ' names{n(j)} ';\n']);
end
end
%m = unique([m{:}]);
fprintf(fid,'\n');
for i=1:size(hrefs,1)
fprintf(fid,[' ' names{i} ' [URL="' ...
fullurl(mdirs{i},[names{i} options.extension]) '"];\n']);
end
else
i = find(strcmp(f,mfiles));
if length(i) ~= 1
error(sprintf('[mdot] Cannot find %s.',f));
end
n = find(hrefs(i,:) == 1);
for j=1:length(n)
fprintf(fid,[' ' names{i} ' -> ' names{n(j)} ';\n']);
end
m = find(hrefs(:,i) == 1);
for j=1:length(m)
if n(j) ~= i
fprintf(fid,[' ' names{m(j)} ' -> ' names{i} ';\n']);
end
end
n = unique([n(:)' m(:)']);
fprintf(fid,'\n');
for i=1:length(n)
fprintf(fid,[' ' names{n(i)} ' [URL="' fullurl(mdirs{i}, ...
[names{n(i)} options.extension]) '"];\n']);
end
end
fprintf(fid,'}');
fid = fclose(fid);
if fid == -1, error(sprintf('[mdot] Cannot close %s.',dotfile)); end
%===========================================================================
function f = fullurl(varargin)
%- Build full url from parts (using '/' and not filesep)
f = strrep(fullfile(varargin{:}),'\','/');
|
github
|
3arbouch/PersonDetection-master
|
m2html.m
|
.m
|
PersonDetection-master/Source/toolbox/external/m2html/m2html.m
| 49,063 |
utf_8
|
472047b4c36a4f8b162012840e31b59b
|
function m2html(varargin)
%M2HTML - Documentation Generator for Matlab M-files and Toolboxes in HTML
% M2HTML by itself generates an HTML documentation of the Matlab M-files found
% in the direct subdirectories of the current directory. HTML files are
% written in a 'doc' directory (created if necessary). All the others options
% are set to default (in brackets in the following).
% M2HTML('PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2,...)
% sets multiple option values. The list of option names and default values is:
% o mFiles - Cell array of strings or character array containing the
% list of M-files and/or directories of M-files for which an HTML
% documentation will be built (use relative paths without backtracking).
% Launch M2HTML one directory above the directory your wanting to
% generate documentation for [ <all direct subdirectories> ]
% o htmlDir - Top level directory for generated HTML files [ 'doc' ]
% o recursive - Process subdirectories recursively [ on | {off} ]
% o source - Include Matlab source code in the generated documentation
% [ {on} | off ]
% o download - Add a link to download each M-file separately [ on | {off} ]
% o syntaxHighlighting - Source Code Syntax Highlighting [ {on} | off ]
% o tabs - Replace '\t' (horizontal tab) in source code by n white space
% characters [ 0 ... {4} ... n ]
% o globalHypertextLinks - Hypertext links among separate Matlab
% directories [ on | {off} ]
% o todo - Create a TODO list in each directory summarizing all the
% '% TODO %' lines found in Matlab code [ on | {off}]
% o graph - Compute a dependency graph using GraphViz [ on | {off}]
% 'dot' required, see <http://www.graphviz.org/>
% o indexFile - Basename of the HTML index file [ 'index' ]
% o extension - Extension of generated HTML files [ '.html' ]
% o template - HTML template name to use [ {'blue'} | 'frame' | ... ]
% o search - Add a PHP search engine [ on | {off}] - beta version!
% o save - Save current state after M-files parsing in 'm2html.mat'
% in directory htmlDir [ on | {off}]
% o load - Load a previously saved '.mat' M2HTML state to generate HTML
% files once again with possibly other options [ <none> ]
% o verbose - Verbose mode [ {on} | off ]
%
% For more information, please read the M2HTML tutorial and FAQ at:
% <http://www.artefact.tk/software/matlab/m2html/>
%
% Examples:
% >> m2html('mfiles','matlab', 'htmldir','doc');
% >> m2html('mfiles',{'matlab/signal' 'matlab/image'}, 'htmldir','doc');
% >> m2html('mfiles','matlab', 'htmldir','doc', 'recursive','on');
% >> m2html('mfiles','mytoolbox', 'htmldir','doc', 'source','off');
% >> m2html('mfiles','matlab', 'htmldir','doc', 'global','on');
% >> m2html( ... , 'template','frame', 'index','menu');
%
% See also MWIZARD, MDOT, TEMPLATE.
% Copyright (C) 2005 Guillaume Flandin <[email protected]>
% $Revision: 1.5 $Date: 2005/04/29 16:04:17 $
% 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 2
% 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, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to [email protected]
% For tips on how to write Matlab code, see:
% * MATLAB Programming Style Guidelines, by R. Johnson:
% <http://www.datatool.com/prod02.htm>
% * For tips on creating help for your m-files 'type help.m'.
% * Matlab documentation on M-file Programming:
% <http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/ch_funh8.html>
% This function uses the Template class so that you can fully customize
% the output. You can modify .tpl files in templates/blue/ or create new
% templates in a new directory.
% See the template class documentation for more details.
% <http://www.artefact.tk/software/matlab/template/>
% Latest information on M2HTML is available on the web through:
% <http://www.artefact.tk/software/matlab/m2html/>
% Other Matlab to HTML converters available on the web:
% 1/ mat2html.pl, J.C. Kantor, in Perl, 1995:
% <http://fresh.t-systems-sfr.com/unix/src/www/mat2html>
% 2/ htmltools, B. Alsberg, in Matlab, 1997:
% <http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=175>
% 3/ mtree2html2001, H. Pohlheim, in Perl, 1996, 2001:
% <http://www.pohlheim.com/perl_main.html#matlabdocu>
% 4/ MatlabToHTML, T. Kristjansson, binary, 2001:
% <http://www.psi.utoronto.ca/~trausti/MatlabToHTML/MatlabToHTML.html>
% 5/ Highlight, G. Flandin, in Matlab, 2003:
% <http://www.artefact.tk/software/matlab/highlight/>
% 6/ mdoc, P. Brinkmann, in Matlab, 2003:
% <http://www.math.uiuc.edu/~brinkman/software/mdoc/>
% 7/ Ocamaweb, Miriad Technologies, in Ocaml, 2002:
% <http://ocamaweb.sourceforge.net/>
% 8/ Matdoc, M. Kaminsky, in Perl, 2003:
% <http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=3498>
% 9/ Matlab itself, The Mathworks Inc, with HELPWIN, DOC and PUBLISH (R14)
%-------------------------------------------------------------------------------
%- Set up options and default parameters
%-------------------------------------------------------------------------------
t0 = clock; % for statistics
msgInvalidPair = 'Bad value for argument: ''%s''';
options = struct('verbose', 1,...
'mFiles', {{'.'}},...
'htmlDir', 'doc',...
'recursive', 0,...
'source', 1,...
'download',0,...
'syntaxHighlighting', 1,...
'tabs', 4,...
'globalHypertextLinks', 0,...
'graph', 0,...
'todo', 0,...
'load', 0,...
'save', 0,...
'search', 0,...
'helptocxml', 0,...
'indexFile', 'index',...
'extension', '.html',...
'template', 'blue',...
'rootdir', pwd,...
'language', 'english');
if nargin == 1 & isstruct(varargin{1})
paramlist = [ fieldnames(varargin{1}) ...
struct2cell(varargin{1}) ]';
paramlist = { paramlist{:} };
else
if mod(nargin,2)
error('Invalid parameter/value pair arguments.');
end
paramlist = varargin;
end
optionsnames = lower(fieldnames(options));
for i=1:2:length(paramlist)
pname = paramlist{i};
pvalue = paramlist{i+1};
ind = strmatch(lower(pname),optionsnames);
if isempty(ind)
error(['Invalid parameter: ''' pname '''.']);
elseif length(ind) > 1
error(['Ambiguous parameter: ''' pname '''.']);
end
switch(optionsnames{ind})
case 'verbose'
if strcmpi(pvalue,'on')
options.verbose = 1;
elseif strcmpi(pvalue,'off')
options.verbose = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'mfiles'
if iscellstr(pvalue)
options.mFiles = pvalue;
elseif ischar(pvalue)
options.mFiles = cellstr(pvalue);
else
error(sprintf(msgInvalidPair,pname));
end
options.load = 0;
case 'htmldir'
if ischar(pvalue)
if isempty(pvalue),
options.htmlDir = '.';
else
options.htmlDir = pvalue;
end
else
error(sprintf(msgInvalidPair,pname));
end
case 'recursive'
if strcmpi(pvalue,'on')
options.recursive = 1;
elseif strcmpi(pvalue,'off')
options.recursive = 0;
else
error(sprintf(msgInvalidPair,pname));
end
options.load = 0;
case 'source'
if strcmpi(pvalue,'on')
options.source = 1;
elseif strcmpi(pvalue,'off')
options.source = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'download'
if strcmpi(pvalue,'on')
options.download = 1;
elseif strcmpi(pvalue,'off')
options.download = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'syntaxhighlighting'
if strcmpi(pvalue,'on')
options.syntaxHighlighting = 1;
elseif strcmpi(pvalue,'off')
options.syntaxHighlighting = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'tabs'
if pvalue >= 0
options.tabs = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
case 'globalhypertextlinks'
if strcmpi(pvalue,'on')
options.globalHypertextLinks = 1;
elseif strcmpi(pvalue,'off')
options.globalHypertextLinks = 0;
else
error(sprintf(msgInvalidPair,pname));
end
options.load = 0;
case 'graph'
if strcmpi(pvalue,'on')
options.graph = 1;
elseif strcmpi(pvalue,'off')
options.graph = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'todo'
if strcmpi(pvalue,'on')
options.todo = 1;
elseif strcmpi(pvalue,'off')
options.todo = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'load'
if ischar(pvalue)
if exist(pvalue) == 7 % directory provided
pvalue = fullfile(pvalue,'m2html.mat');
end
try
load(pvalue);
catch
error(sprintf('Unable to load %s.', pvalue));
end
options.load = 1;
[dummy options.template] = fileparts(options.template);
else
error(sprintf(msgInvalidPair,pname));
end
case 'save'
if strcmpi(pvalue,'on')
options.save = 1;
elseif strcmpi(pvalue,'off')
options.save = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'search'
if strcmpi(pvalue,'on')
options.search = 1;
elseif strcmpi(pvalue,'off')
options.search = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'helptocxml'
if strcmpi(pvalue,'on')
options.helptocxml = 1;
elseif strcmpi(pvalue,'off')
options.helptocxml = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'indexfile'
if ischar(pvalue)
options.indexFile = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
case 'extension'
if ischar(pvalue) & pvalue(1) == '.'
options.extension = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
case 'template'
if ischar(pvalue)
options.template = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
case 'language'
if ischar(pvalue)
options.language = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
otherwise
error(['Invalid parameter: ''' pname '''.']);
end
end
%-------------------------------------------------------------------------------
%- Get template files location
%-------------------------------------------------------------------------------
s = fileparts(which(mfilename));
options.template = fullfile(s,'templates',options.template);
if exist(options.template) ~= 7
error('[Template] Unknown template.');
end
%-------------------------------------------------------------------------------
%- Get list of M-files
%-------------------------------------------------------------------------------
if ~options.load
if strcmp(options.mFiles,'.')
d = dir(pwd); d = {d([d.isdir]).name};
options.mFiles = {d{~ismember(d,{'.' '..'})}};
end
mfiles = getmfiles(options.mFiles,{},options.recursive);
if ~length(mfiles), fprintf('Nothing to be done.\n'); return; end
if options.verbose,
fprintf('Found %d M-files.\n',length(mfiles));
end
mfiles = sort(mfiles); % sort list of M-files in dictionary order
end
%-------------------------------------------------------------------------------
%- Get list of (unique) directories and (unique) names
%-------------------------------------------------------------------------------
if ~options.load
mdirs = {};
names = {};
for i=1:length(mfiles)
[mdirs{i}, names{i}] = fileparts(mfiles{i});
if isempty(mdirs{i}), mdirs{i} = '.'; end
end
mdir = unique(mdirs);
if options.verbose,
fprintf('Found %d unique Matlab directories.\n',length(mdir));
end
name = names;
%name = unique(names); % output is sorted
%if options.verbose,
% fprintf('Found %d unique Matlab files.\n',length(name));
%end
end
%-------------------------------------------------------------------------------
%- Create output directory, if necessary
%-------------------------------------------------------------------------------
if isempty(dir(options.htmlDir))
%- Create the top level output directory
if options.verbose
fprintf('Creating directory %s...\n',options.htmlDir);
end
if options.htmlDir(end) == filesep,
options.htmlDir(end) = [];
end
[pathdir, namedir] = fileparts(options.htmlDir);
if isempty(pathdir)
[status, msg] = mkdir(escapeblank(namedir));
else
[status, msg] = mkdir(escapeblank(pathdir), escapeblank(namedir));
end
if ~status, error(msg); end
end
%-------------------------------------------------------------------------------
%- Get synopsis, H1 line, script/function, subroutines, cross-references, todo
%-------------------------------------------------------------------------------
if ~options.load
synopsis = cell(size(mfiles));
h1line = cell(size(mfiles));
subroutine = cell(size(mfiles));
hrefs = sparse(length(mfiles), length(mfiles));
todo = struct('mfile',[], 'line',[], 'comment',{{}});
ismex = zeros(length(mfiles), length(mexexts));
statlist = {};
statinfo = sparse(1,length(mfiles));
kw = cell(size(mfiles));
freq = cell(size(mfiles));
for i=1:length(mfiles)
if options.verbose
fprintf('Processing file %s...',mfiles{i});
end
s = mfileparse(mfiles{i}, mdirs, names, options);
synopsis{i} = s.synopsis;
h1line{i} = s.h1line;
subroutine{i} = s.subroutine;
hrefs(i,:) = s.hrefs;
todo.mfile = [todo.mfile repmat(i,1,length(s.todo.line))];
todo.line = [todo.line s.todo.line];
todo.comment = {todo.comment{:} s.todo.comment{:}};
ismex(i,:) = s.ismex;
if options.search
if options.verbose, fprintf('search...'); end
[kw{i}, freq{i}] = searchindex(mfiles{i});
statlist = union(statlist, kw{i});
end
if options.verbose, fprintf('\n'); end
end
hrefs = hrefs > 0;
if options.search
if options.verbose
fprintf('Creating the search index...');
end
statinfo = sparse(length(statlist),length(mfiles));
for i=1:length(mfiles)
i1 = find(ismember(statlist, kw{i}));
i2 = repmat(i,1,length(i1));
if ~isempty(i1)
statinfo(sub2ind(size(statinfo),i1,i2)) = freq{i};
end
if options.verbose, fprintf('.'); end
end
clear kw freq;
if options.verbose, fprintf('\n'); end
end
end
%-------------------------------------------------------------------------------
%- Save M-filenames and cross-references for further analysis
%-------------------------------------------------------------------------------
matfilesave = 'm2html.mat';
if options.save
if options.verbose
fprintf('Saving MAT file %s...\n',matfilesave);
end
save(fullfile(options.htmlDir,matfilesave), ...
'mfiles', 'names', 'mdirs', 'name', 'mdir', 'options', ...
'hrefs', 'synopsis', 'h1line', 'subroutine', 'todo', 'ismex', ...
'statlist', 'statinfo');
end
%-------------------------------------------------------------------------------
%- Setup the output directories
%-------------------------------------------------------------------------------
for i=1:length(mdir)
if exist(fullfile(options.htmlDir,mdir{i})) ~= 7
ldir = splitpath(mdir{i});
for j=1:length(ldir)
if exist(fullfile(options.htmlDir,ldir{1:j})) ~= 7
%- Create the output directory
if options.verbose
fprintf('Creating directory %s...\n',...
fullfile(options.htmlDir,ldir{1:j}));
end
if j == 1
[status, msg] = mkdir(escapeblank(options.htmlDir), ...
escapeblank(ldir{1}));
else
[status, msg] = mkdir(escapeblank(options.htmlDir), ...
escapeblank(fullfile(ldir{1:j})));
end
error(msg);
end
end
end
end
%-------------------------------------------------------------------------------
%- Write the master index file
%-------------------------------------------------------------------------------
tpl_master = 'master.tpl';
tpl_master_identifier_nbyline = 4;
php_search = 'search.php';
dotbase = 'graph';
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_MASTER',tpl_master);
tpl = set(tpl,'block','TPL_MASTER','rowdir','rowdirs');
tpl = set(tpl,'block','TPL_MASTER','idrow','idrows');
tpl = set(tpl,'block','idrow','idcolumn','idcolumns');
tpl = set(tpl,'block','TPL_MASTER','search','searchs');
tpl = set(tpl,'block','TPL_MASTER','graph','graphs');
%- Open for writing the HTML master index file
curfile = fullfile(options.htmlDir,[options.indexFile options.extension]);
if options.verbose
fprintf('Creating HTML file %s...\n',curfile);
end
fid = openfile(curfile,'w');
%- Set some template variables
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
tpl = set(tpl,'var','MASTERPATH', './');
tpl = set(tpl,'var','DIRS', sprintf('%s ',mdir{:}));
%- Print list of unique directories
for i=1:length(mdir)
tpl = set(tpl,'var','L_DIR',...
fullurl(mdir{i},[options.indexFile options.extension]));
tpl = set(tpl,'var','DIR',mdir{i});
tpl = parse(tpl,'rowdirs','rowdir',1);
end
%- Print full list of M-files (sorted by column)
[sortnames, ind] = sort(names);
m_mod = mod(length(sortnames), tpl_master_identifier_nbyline);
ind = [ind zeros(1,tpl_master_identifier_nbyline-m_mod)];
m_floor = floor(length(ind) / tpl_master_identifier_nbyline);
ind = reshape(ind,m_floor,tpl_master_identifier_nbyline)';
for i=1:prod(size(ind))
if ind(i)
tpl = set(tpl,'var','L_IDNAME',...
fullurl(mdirs{ind(i)},[names{ind(i)} options.extension]));
tpl = set(tpl,'var','T_IDNAME',mdirs{ind(i)});
tpl = set(tpl,'var','IDNAME',names{ind(i)});
tpl = parse(tpl,'idcolumns','idcolumn',1);
else
tpl = set(tpl,'var','L_IDNAME','');
tpl = set(tpl,'var','T_IDNAME','');
tpl = set(tpl,'var','IDNAME','');
tpl = parse(tpl,'idcolumns','idcolumn',1);
end
if mod(i,tpl_master_identifier_nbyline) == 0
tpl = parse(tpl,'idrows','idrow',1);
tpl = set(tpl,'var','idcolumns','');
end
end
%- Add a search form if necessary
tpl = set(tpl,'var','searchs','');
if options.search
tpl = set(tpl,'var','PHPFILE',php_search);
tpl = parse(tpl,'searchs','search',1);
end
%- Link to a full dependency graph, if necessary
tpl = set(tpl,'var','graphs','');
if options.graph & options.globalHypertextLinks & length(mdir) > 1
tpl = set(tpl,'var','LGRAPH',[dotbase options.extension]);
tpl = parse(tpl,'graphs','graph',1);
end
%- Print the template in the HTML file
tpl = parse(tpl,'OUT','TPL_MASTER');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid);
%-------------------------------------------------------------------------------
%- Copy template files (CSS, images, ...)
%-------------------------------------------------------------------------------
% Get list of files
d = dir(options.template);
d = {d(~[d.isdir]).name};
% Copy files
for i=1:length(d)
[p, n, ext] = fileparts(d{i});
if ~strcmp(ext,'.tpl') ... % do not copy .tpl files
& ~strcmp([n ext],'Thumbs.db') % do not copy this Windows generated file
if isempty(dir(fullfile(options.htmlDir,d{i})))
if options.verbose
fprintf('Copying template file %s...\n',d{i});
end
%- there is a bug with <copyfile> in Matlab 6.5 :
% http://www.mathworks.com/support/solutions/data/1-1B5JY.html
%- and <copyfile> does not overwrite files even if newer...
[status, errmsg] = copyfile(fullfile(options.template,d{i}),...
options.htmlDir);
%- If you encounter this bug, please uncomment one of the following lines
% eval(['!cp -rf ' fullfile(options.template,d{i}) ' ' options.htmlDir]);
% eval(['!copy ' fullfile(options.template,d{i}) ' ' options.htmlDir]);
% status = 1;
if ~status
if ~isempty(errmsg)
error(errmsg)
else
warning(sprintf(['<copyfile> failed to do its job...\n' ...
'This is a known bug in Matlab 6.5 (R13).\n' ...
'See http://www.mathworks.com/support/solutions/data/1-1B5JY.html']));
end
end
end
end
end
%-------------------------------------------------------------------------------
%- Search engine (index file and PHP script)
%-------------------------------------------------------------------------------
tpl_search = 'search.tpl';
idx_search = 'search.idx';
% TODO % improving the fill in of 'statlist' and 'statinfo'
% TODO % improving the search template file and update the CSS file
if options.search
%- Write the search index file in output directory
if options.verbose
fprintf('Creating Search Index file %s...\n', idx_search);
end
docinfo = cell(length(mfiles),2);
for i=1:length(mfiles)
docinfo{i,1} = h1line{i};
docinfo{i,2} = fullurl(mdirs{i}, [names{i} options.extension]);
end
doxywrite(fullfile(options.htmlDir,idx_search),statlist,statinfo,docinfo);
%- Create the PHP template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_SEARCH',tpl_search);
%- Open for writing the PHP search script
curfile = fullfile(options.htmlDir, php_search);
if options.verbose
fprintf('Creating PHP script %s...\n',curfile);
end
fid = openfile(curfile,'w');
%- Set template fields
tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH','./');
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
tpl = set(tpl,'var','IDXFILE',idx_search);
tpl = set(tpl,'var','PHPFILE',php_search);
%- Print the template in the HTML file
tpl = parse(tpl,'OUT','TPL_SEARCH');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid);
end
%-------------------------------------------------------------------------------
%- Create <helptoc.xml> needed to display hierarchical entries in Contents panel
%-------------------------------------------------------------------------------
% See http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/guiref16.html
% and http://www.mathworks.com/support/solutions/data/1-18U6Q.html?solution=1-18U6Q
% TODO % display directories in TOC hierarchically instead of linearly
if options.helptocxml
curfile = fullfile(options.htmlDir, 'helptoc.xml');
if options.verbose
fprintf('Creating XML Table-Of-Content %s...\n',curfile);
end
fid = openfile(curfile,'w');
fprintf(fid,'<?xml version=''1.0'' encoding=''ISO-8859-1'' ?>\n');
fprintf(fid,'<!-- $Date: %s $ -->\n\n', datestr(now,31));
fprintf(fid,'<toc version="1.0">\n\n');
fprintf(fid,['<tocitem target="%s" ',...
'image="$toolbox/matlab/icons/book_mat.gif">%s\n'], ...
[options.indexFile options.extension],'Toolbox');
for i=1:length(mdir)
fprintf(fid,['<tocitem target="%s" ',...
'image="$toolbox/matlab/icons/reficon.gif">%s\n'], ...
fullfile(mdir{i}, ...
[options.indexFile options.extension]),mdir{i});
if options.graph
fprintf(fid,['\t<tocitem target="%s" ',...
'image="$toolbox/matlab/icons/simulinkicon.gif">%s</tocitem>\n'], ...
fullfile(mdir{i},...
[dotbase options.extension]),'Dependency Graph');
end
if options.todo
if ~isempty(intersect(find(strcmp(mdir{i},mdirs)),todo.mfile))
fprintf(fid,['\t<tocitem target="%s" ',...
'image="$toolbox/matlab/icons/demoicon.gif">%s</tocitem>\n'], ...
fullfile(mdir{i},...
['todo' options.extension]),'Todo list');
end
end
for j=1:length(mdirs)
if strcmp(mdirs{j},mdir{i})
curfile = fullfile(mdir{i},...
[names{j} options.extension]);
fprintf(fid,'\t<tocitem target="%s">%s</tocitem>\n', ...
curfile,names{j});
end
end
fprintf(fid,'</tocitem>\n');
end
fprintf(fid,'</tocitem>\n');
fprintf(fid,'\n</toc>\n');
fclose(fid);
end
%-------------------------------------------------------------------------------
%- Write an index for each output directory
%-------------------------------------------------------------------------------
tpl_mdir = 'mdir.tpl';
tpl_mdir_link = '<a href="%s">%s</a>';
%dotbase defined earlier
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_MDIR',tpl_mdir);
tpl = set(tpl,'block','TPL_MDIR','row-m','rows-m');
tpl = set(tpl,'block','row-m','mexfile','mex');
tpl = set(tpl,'block','TPL_MDIR','othermatlab','other');
tpl = set(tpl,'block','othermatlab','row-other','rows-other');
tpl = set(tpl,'block','TPL_MDIR','subfolder','subfold');
tpl = set(tpl,'block','subfolder','subdir','subdirs');
tpl = set(tpl,'block','TPL_MDIR','todolist','todolists');
tpl = set(tpl,'block','TPL_MDIR','graph','graphs');
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
for i=1:length(mdir)
%- Open for writing each output directory index file
curfile = fullfile(options.htmlDir,mdir{i},...
[options.indexFile options.extension]);
if options.verbose
fprintf('Creating HTML file %s...\n',curfile);
end
fid = openfile(curfile,'w');
%- Set template fields
tpl = set(tpl,'var','INDEX', [options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH',backtomaster(mdir{i}));
tpl = set(tpl,'var','MDIR', mdir{i});
%- Display Matlab m-files, their H1 line and their Mex status
tpl = set(tpl,'var','rows-m','');
for j=1:length(mdirs)
if strcmp(mdirs{j},mdir{i})
tpl = set(tpl,'var','L_NAME', [names{j} options.extension]);
tpl = set(tpl,'var','NAME', names{j});
tpl = set(tpl,'var','H1LINE', h1line{j});
if any(ismex(j,:))
tpl = parse(tpl,'mex','mexfile');
else
tpl = set(tpl,'var','mex','');
end
tpl = parse(tpl,'rows-m','row-m',1);
end
end
%- Display other Matlab-specific files (.mat,.mdl,.p)
tpl = set(tpl,'var','other','');
tpl = set(tpl,'var','rows-other','');
w = what(mdir{i}); w = w(1);
w = {w.mat{:} w.mdl{:} w.p{:}};
for j=1:length(w)
tpl = set(tpl,'var','OTHERFILE',w{j});
tpl = parse(tpl,'rows-other','row-other',1);
end
if ~isempty(w)
tpl = parse(tpl,'other','othermatlab');
end
%- Display subsequent directories and classes
tpl = set(tpl,'var','subdirs','');
tpl = set(tpl,'var','subfold','');
d = dir(mdir{i});
d = {d([d.isdir]).name};
d = {d{~ismember(d,{'.' '..'})}};
for j=1:length(d)
if ismember(fullfile(mdir{i},d{j}),mdir)
tpl = set(tpl,'var','SUBDIRECTORY',...
sprintf(tpl_mdir_link,...
fullurl(d{j},[options.indexFile options.extension]),d{j}));
else
tpl = set(tpl,'var','SUBDIRECTORY',d{j});
end
tpl = parse(tpl,'subdirs','subdir',1);
end
if ~isempty(d)
tpl = parse(tpl,'subfold','subfolder');
end
%- Link to the TODO list if necessary
tpl = set(tpl,'var','todolists','');
if options.todo
if ~isempty(intersect(find(strcmp(mdir{i},mdirs)),todo.mfile))
tpl = set(tpl,'var','LTODOLIST',['todo' options.extension]);
tpl = parse(tpl,'todolists','todolist',1);
end
end
%- Link to the dependency graph if necessary
tpl = set(tpl,'var','graphs','');
if options.graph
tpl = set(tpl,'var','LGRAPH',[dotbase options.extension]);
tpl = parse(tpl,'graphs','graph',1);
end
%- Print the template in the HTML file
tpl = parse(tpl,'OUT','TPL_MDIR');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid);
end
%-------------------------------------------------------------------------------
%- Write a TODO list file for each output directory, if necessary
%-------------------------------------------------------------------------------
tpl_todo = 'todo.tpl';
if options.todo
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_TODO',tpl_todo);
tpl = set(tpl,'block','TPL_TODO','filelist','filelists');
tpl = set(tpl,'block','filelist','row','rows');
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
for i=1:length(mdir)
mfilestodo = intersect(find(strcmp(mdir{i},mdirs)),todo.mfile);
if ~isempty(mfilestodo)
%- Open for writing each TODO list file
curfile = fullfile(options.htmlDir,mdir{i},...
['todo' options.extension]);
if options.verbose
fprintf('Creating HTML file %s...\n',curfile);
end
fid = openfile(curfile,'w');
%- Set template fields
tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i}));
tpl = set(tpl,'var','MDIR', mdir{i});
tpl = set(tpl,'var','filelists', '');
for k=1:length(mfilestodo)
tpl = set(tpl,'var','MFILE',names{mfilestodo(k)});
tpl = set(tpl,'var','rows','');
nbtodo = find(todo.mfile == mfilestodo(k));
for l=1:length(nbtodo)
tpl = set(tpl,'var','L_NBLINE',...
[names{mfilestodo(k)} ...
options.extension ...
'#l' num2str(todo.line(nbtodo(l)))]);
tpl = set(tpl,'var','NBLINE',num2str(todo.line(nbtodo(l))));
tpl = set(tpl,'var','COMMENT',todo.comment{nbtodo(l)});
tpl = parse(tpl,'rows','row',1);
end
tpl = parse(tpl,'filelists','filelist',1);
end
%- Print the template in the HTML file
tpl = parse(tpl,'OUT','TPL_TODO');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid);
end
end
end
%-------------------------------------------------------------------------------
%- Create dependency graphs using GraphViz, if requested
%-------------------------------------------------------------------------------
tpl_graph = 'graph.tpl';
% You may have to modify the following line with Matlab7 (R14) to specify
% the full path to where GraphViz is installed
dot_exec = 'dot';
%dotbase defined earlier
if options.graph
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_GRAPH',tpl_graph);
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
%- Create a full dependency graph for all directories if possible
if options.globalHypertextLinks & length(mdir) > 1
mdotfile = fullfile(options.htmlDir,[dotbase '.dot']);
if options.verbose
fprintf('Creating full dependency graph %s...',mdotfile);
end
mdot({hrefs, names, options, mdirs}, mdotfile); %mfiles
calldot(dot_exec, mdotfile, ...
fullfile(options.htmlDir,[dotbase '.map']), ...
fullfile(options.htmlDir,[dotbase '.png']));
if options.verbose, fprintf('\n'); end
fid = openfile(fullfile(options.htmlDir, [dotbase options.extension]),'w');
tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH', './');
tpl = set(tpl,'var','MDIR', 'the whole toolbox');
tpl = set(tpl,'var','GRAPH_IMG', [dotbase '.png']);
try % if <dot> failed...
fmap = openfile(fullfile(options.htmlDir,[dotbase '.map']),'r');
tpl = set(tpl,'var','GRAPH_MAP', fscanf(fmap,'%c'));
fclose(fmap);
end
tpl = parse(tpl,'OUT','TPL_GRAPH');
fprintf(fid,'%s', get(tpl,'OUT'));
fclose(fid);
end
%- Create a dependency graph for each output directory
for i=1:length(mdir)
mdotfile = fullfile(options.htmlDir,mdir{i},[dotbase '.dot']);
if options.verbose
fprintf('Creating dependency graph %s...',mdotfile);
end
ind = find(strcmp(mdirs,mdir{i}));
href1 = zeros(length(ind),length(hrefs));
for j=1:length(hrefs), href1(:,j) = hrefs(ind,j); end
href2 = zeros(length(ind));
for j=1:length(ind), href2(j,:) = href1(j,ind); end
mdot({href2, {names{ind}}, options}, mdotfile); %{mfiles{ind}}
calldot(dot_exec, mdotfile, ...
fullfile(options.htmlDir,mdir{i},[dotbase '.map']), ...
fullfile(options.htmlDir,mdir{i},[dotbase '.png']));
if options.verbose, fprintf('\n'); end
fid = openfile(fullfile(options.htmlDir,mdir{i},...
[dotbase options.extension]),'w');
tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i}));
tpl = set(tpl,'var','MDIR', mdir{i});
tpl = set(tpl,'var','GRAPH_IMG', [dotbase '.png']);
try % if <dot> failed, no '.map' file has been created
fmap = openfile(fullfile(options.htmlDir,mdir{i},[dotbase '.map']),'r');
tpl = set(tpl,'var','GRAPH_MAP', fscanf(fmap,'%c'));
fclose(fmap);
end
tpl = parse(tpl,'OUT','TPL_GRAPH');
fprintf(fid,'%s', get(tpl,'OUT'));
fclose(fid);
end
end
%-------------------------------------------------------------------------------
%- Write an HTML file for each M-file
%-------------------------------------------------------------------------------
%- List of Matlab keywords (output from iskeyword)
matlabKeywords = {'break', 'case', 'catch', 'continue', 'elseif', 'else', ...
'end', 'for', 'function', 'global', 'if', 'otherwise', ...
'persistent', 'return', 'switch', 'try', 'while'};
%'keyboard', 'pause', 'eps', 'NaN', 'Inf'
tpl_mfile = 'mfile.tpl';
tpl_mfile_code = '<a href="%s" class="code" title="%s">%s</a>';
tpl_mfile_keyword = '<span class="keyword">%s</span>';
tpl_mfile_comment = '<span class="comment">%s</span>';
tpl_mfile_string = '<span class="string">%s</span>';
tpl_mfile_aname = '<a name="%s" href="#_subfunctions" class="code">%s</a>';
tpl_mfile_line = '%04d %s\n';
%- Delimiters used in strtok: some of them may be useless (% " .), removed '.'
strtok_delim = sprintf(' \t\n\r(){}[]<>+-*~!|\\@&/,:;="''%%');
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_MFILE',tpl_mfile);
tpl = set(tpl,'block','TPL_MFILE','pathline','pl');
tpl = set(tpl,'block','TPL_MFILE','mexfile','mex');
tpl = set(tpl,'block','TPL_MFILE','script','scriptfile');
tpl = set(tpl,'block','TPL_MFILE','crossrefcall','crossrefcalls');
tpl = set(tpl,'block','TPL_MFILE','crossrefcalled','crossrefcalleds');
tpl = set(tpl,'block','TPL_MFILE','subfunction','subf');
tpl = set(tpl,'block','subfunction','onesubfunction','onesubf');
tpl = set(tpl,'block','TPL_MFILE','source','thesource');
tpl = set(tpl,'block','TPL_MFILE','download','downloads');
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
nblinetot = 0;
for i=1:length(mdir)
for j=1:length(mdirs)
if strcmp(mdirs{j},mdir{i})
curfile = fullfile(options.htmlDir,mdir{i},...
[names{j} options.extension]);
%- Copy M-file for download, if necessary
if options.download
if options.verbose
fprintf('Copying M-file %s.m to %s...\n',names{j},...
fullfile(options.htmlDir,mdir{i}));
end
[status, errmsg] = copyfile(mfiles{j},...
fullfile(options.htmlDir,mdir{i}));
error(errmsg);
end
%- Open for writing the HTML file
if options.verbose
fprintf('Creating HTML file %s...\n',curfile);
end
fid = openfile(curfile,'w');
if strcmp(names{j},options.indexFile)
fprintf(['Warning: HTML index file %s will be ' ...
'overwritten by Matlab function %s.\n'], ...
[options.indexFile options.extension], mfiles{j});
end
%- Open for reading the M-file
fid2 = openfile(mfiles{j},'r');
%- Set some template fields
tpl = set(tpl,'var','INDEX', [options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i}));
tpl = set(tpl,'var','MDIR', mdirs{j});
tpl = set(tpl,'var','NAME', names{j});
tpl = set(tpl,'var','H1LINE', entity(h1line{j}));
tpl = set(tpl,'var','scriptfile', '');
if isempty(synopsis{j})
tpl = set(tpl,'var','SYNOPSIS',get(tpl,'var','script'));
else
tpl = set(tpl,'var','SYNOPSIS', synopsis{j});
end
s = splitpath(mdir{i});
tpl = set(tpl,'var','pl','');
for k=1:length(s)
c = cell(1,k); for l=1:k, c{l} = filesep; end
cpath = {s{1:k};c{:}}; cpath = [cpath{:}];
if ~isempty(cpath), cpath = cpath(1:end-1); end
if ismember(cpath,mdir)
tpl = set(tpl,'var','LPATHDIR',[repmat('../',...
1,length(s)-k) options.indexFile options.extension]);
else
tpl = set(tpl,'var','LPATHDIR','#');
end
tpl = set(tpl,'var','PATHDIR',s{k});
tpl = parse(tpl,'pl','pathline',1);
end
%- Handle mex files
tpl = set(tpl,'var','mex', '');
samename = dir(fullfile(mdir{i},[names{j} '.*']));
samename = {samename.name};
tpl = set(tpl,'var','MEXTYPE', 'mex');
for k=1:length(samename)
[dummy, dummy, ext] = fileparts(samename{k});
switch ext
case '.c'
tpl = set(tpl,'var','MEXTYPE', 'c');
case {'.cpp' '.c++' '.cxx' '.C'}
tpl = set(tpl,'var','MEXTYPE', 'c++');
case {'.for' '.f' '.FOR' '.F'}
tpl = set(tpl,'var','MEXTYPE', 'fortran');
otherwise
%- Unknown mex file source
end
end
[exts, platform] = mexexts;
mexplatforms = sprintf('%s, ',platform{find(ismex(j,:))});
if ~isempty(mexplatforms)
tpl = set(tpl,'var','PLATFORMS', mexplatforms(1:end-2));
tpl = parse(tpl,'mex','mexfile');
end
%- Set description template field
descr = '';
flagsynopcont = 0;
flag_seealso = 0;
while 1
tline = fgets(fid2);
if ~ischar(tline), break, end
tline = entity(fliplr(deblank(fliplr(tline))));
%- Synopsis line
if ~isempty(strmatch('function',tline))
if ~isempty(strmatch('...',fliplr(deblank(tline))))
flagsynopcont = 1;
end
%- H1 line and description
elseif ~isempty(strmatch('%',tline))
%- Hypertext links on the "See also" line
ind = findstr(lower(tline),'see also');
if ~isempty(ind) | flag_seealso
%- "See also" only in files in the same directory
indsamedir = find(strcmp(mdirs{j},mdirs));
hrefnames = {names{indsamedir}};
r = deblank(tline);
flag_seealso = 1; %(r(end) == ',');
tline = '';
while 1
[t,r,q] = strtok(r,sprintf(' \t\n\r.,;%%'));
tline = [tline q];
if isempty(t), break, end;
ii = strcmpi(hrefnames,t);
if any(ii)
jj = find(ii);
tline = [tline sprintf(tpl_mfile_code,...
[hrefnames{jj(1)} options.extension],...
synopsis{indsamedir(jj(1))},t)];
else
tline = [tline t];
end
end
tline = sprintf('%s\n',tline);
end
descr = [descr tline(2:end)];
elseif isempty(tline)
if ~isempty(descr), break, end;
else
if flagsynopcont
if isempty(strmatch('...',fliplr(deblank(tline))))
flagsynopcont = 0;
end
else
break;
end
end
end
tpl = set(tpl,'var','DESCRIPTION',...
horztab(descr,options.tabs));
%- Set cross-references template fields:
% Function called
ind = find(hrefs(j,:) == 1);
tpl = set(tpl,'var','crossrefcalls','');
for k=1:length(ind)
if strcmp(mdirs{j},mdirs{ind(k)})
tpl = set(tpl,'var','L_NAME_CALL', ...
[names{ind(k)} options.extension]);
else
tpl = set(tpl,'var','L_NAME_CALL', ...
fullurl(backtomaster(mdirs{j}), ...
mdirs{ind(k)}, ...
[names{ind(k)} options.extension]));
end
tpl = set(tpl,'var','SYNOP_CALL', synopsis{ind(k)});
tpl = set(tpl,'var','NAME_CALL', names{ind(k)});
tpl = set(tpl,'var','H1LINE_CALL', h1line{ind(k)});
tpl = parse(tpl,'crossrefcalls','crossrefcall',1);
end
% Callers
ind = find(hrefs(:,j) == 1);
tpl = set(tpl,'var','crossrefcalleds','');
for k=1:length(ind)
if strcmp(mdirs{j},mdirs{ind(k)})
tpl = set(tpl,'var','L_NAME_CALLED', ...
[names{ind(k)} options.extension]);
else
tpl = set(tpl,'var','L_NAME_CALLED', ...
fullurl(backtomaster(mdirs{j}),...
mdirs{ind(k)}, ...
[names{ind(k)} options.extension]));
end
tpl = set(tpl,'var','SYNOP_CALLED', synopsis{ind(k)});
tpl = set(tpl,'var','NAME_CALLED', names{ind(k)});
tpl = set(tpl,'var','H1LINE_CALLED', h1line{ind(k)});
tpl = parse(tpl,'crossrefcalleds','crossrefcalled',1);
end
%- Set subfunction template field
tpl = set(tpl,'var',{'subf' 'onesubf'},{'' ''});
if ~isempty(subroutine{j}) & options.source
for k=1:length(subroutine{j})
tpl = set(tpl, 'var', 'L_SUB', ['#_sub' num2str(k)]);
tpl = set(tpl, 'var', 'SUB', subroutine{j}{k});
tpl = parse(tpl, 'onesubf', 'onesubfunction',1);
end
tpl = parse(tpl,'subf','subfunction');
end
subname = extractname(subroutine{j});
%- Link to M-file (for download)
tpl = set(tpl,'var','downloads','');
if options.download
tpl = parse(tpl,'downloads','download',1);
end
%- Display source code with cross-references
if options.source & ~strcmpi(names{j},'contents')
fseek(fid2,0,-1);
it = 1;
matlabsource = '';
nbsubroutine = 1;
%- Get href function names of this file
indhrefnames = find(hrefs(j,:) == 1);
hrefnames = {names{indhrefnames}};
%- Loop over lines
while 1
tline = fgetl(fid2);
if ~ischar(tline), break, end
myline = '';
splitc = splitcode(entity(tline));
for k=1:length(splitc)
if isempty(splitc{k})
elseif ~isempty(strmatch('function',splitc{k}))
%- Subfunctions definition
myline = [myline ...
sprintf(tpl_mfile_aname,...
['_sub' num2str(nbsubroutine-1)],splitc{k})];
nbsubroutine = nbsubroutine + 1;
elseif splitc{k}(1) == ''''
myline = [myline ...
sprintf(tpl_mfile_string,splitc{k})];
elseif splitc{k}(1) == '%'
myline = [myline ...
sprintf(tpl_mfile_comment,deblank(splitc{k}))];
elseif ~isempty(strmatch('...',splitc{k}))
myline = [myline sprintf(tpl_mfile_keyword,'...')];
if ~isempty(splitc{k}(4:end))
myline = [myline ...
sprintf(tpl_mfile_comment,splitc{k}(4:end))];
end
else
%- Look for keywords
r = splitc{k};
while 1
[t,r,q] = strtok(r,strtok_delim);
myline = [myline q];
if isempty(t), break, end;
%- Highlight Matlab keywords &
% cross-references on known functions
if options.syntaxHighlighting & ...
any(strcmp(matlabKeywords,t))
if strcmp('end',t)
rr = fliplr(deblank(fliplr(r)));
icomma = strmatch(',',rr);
isemicolon = strmatch(';',rr);
if ~(isempty(rr) | ~isempty([icomma isemicolon]))
myline = [myline t];
else
myline = [myline sprintf(tpl_mfile_keyword,t)];
end
else
myline = [myline sprintf(tpl_mfile_keyword,t)];
end
elseif any(strcmp(hrefnames,t))
indt = indhrefnames(logical(strcmp(hrefnames,t)));
flink = [t options.extension];
ii = ismember({mdirs{indt}},mdirs{j});
if ~any(ii)
% take the first one...
flink = fullurl(backtomaster(mdirs{j}),...
mdirs{indt(1)}, flink);
else
indt = indt(logical(ii));
end
myline = [myline sprintf(tpl_mfile_code,...
flink, synopsis{indt(1)}, t)];
elseif any(strcmp(subname,t))
ii = find(strcmp(subname,t));
myline = [myline sprintf(tpl_mfile_code,...
['#_sub' num2str(ii)],...
['sub' subroutine{j}{ii}],t)];
else
myline = [myline t];
end
end
end
end
matlabsource = [matlabsource sprintf(tpl_mfile_line,it,myline)];
it = it + 1;
end
nblinetot = nblinetot + it - 1;
tpl = set(tpl,'var','SOURCECODE',...
horztab(matlabsource,options.tabs));
tpl = parse(tpl,'thesource','source');
else
tpl = set(tpl,'var','thesource','');
end
tpl = parse(tpl,'OUT','TPL_MFILE');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid2);
fclose(fid);
end
end
end
%-------------------------------------------------------------------------------
%- Display Statistics
%-------------------------------------------------------------------------------
if options.verbose
prnbline = '';
if options.source
prnbline = sprintf('(%d lines) ', nblinetot);
end
fprintf('Stats: %d M-files %sin %d directories documented in %d s.\n', ...
length(mfiles), prnbline, length(mdir), round(etime(clock,t0)));
end
%===============================================================================
function mfiles = getmfiles(mdirs, mfiles, recursive)
%- Extract M-files from a list of directories and/or M-files
for i=1:length(mdirs)
currentdir = fullfile(pwd, mdirs{i});
if exist(currentdir) == 2 % M-file
mfiles{end+1} = mdirs{i};
elseif exist(currentdir) == 7 % Directory
d = dir(fullfile(currentdir, '*.m'));
d = {d(~[d.isdir]).name};
for j=1:length(d)
%- don't take care of files containing ','
% probably a sccs file...
if isempty(findstr(',',d{j}))
mfiles{end+1} = fullfile(mdirs{i}, d{j});
end
end
if recursive
d = dir(currentdir);
d = {d([d.isdir]).name};
d = {d{~ismember(d,{'.' '..'})}};
for j=1:length(d)
mfiles = getmfiles(cellstr(fullfile(mdirs{i},d{j})), ...
mfiles, recursive);
end
end
else
fprintf('Warning: Unprocessed file %s.\n',mdirs{i});
if ~isempty(strmatch('/',mdirs{i})) | findstr(':',mdirs{i})
fprintf(' Use relative paths in ''mfiles'' option\n');
end
end
end
%===============================================================================
function calldot(dotexec, mdotfile, mapfile, pngfile, opt)
%- Draw a dependency graph in a PNG image using <dot> from GraphViz
if nargin == 4, opt = ''; end
try
%- See <http://www.graphviz.org/>
% <dot> must be in your system path, see M2HTML FAQ:
% <http://www.artefact.tk/software/matlab/m2html/faq.php>
eval(['!"' dotexec '" ' opt ' -Tcmap -Tpng "' mdotfile ...
'" -o "' mapfile ...
'" -o "' pngfile '"']);
% use '!' rather than 'system' for backward compability with Matlab 5.3
catch % use of '!' prevents errors to be catched...
fprintf('<dot> failed.');
end
%===============================================================================
function s = backtomaster(mdir)
%- Provide filesystem path to go back to the root folder
ldir = splitpath(mdir);
s = repmat('../',1,length(ldir));
%===============================================================================
function ldir = splitpath(p)
%- Split a filesystem path into parts using filesep as separator
ldir = {};
p = deblank(p);
while 1
[t,p] = strtok(p,filesep);
if isempty(t), break; end
if ~strcmp(t,'.')
ldir{end+1} = t;
end
end
if isempty(ldir)
ldir{1} = '.'; % should be removed
end
%===============================================================================
function name = extractname(synopsis)
%- Extract function name in a synopsis
if ischar(synopsis), synopsis = {synopsis}; end
name = cell(size(synopsis));
for i=1:length(synopsis)
ind = findstr(synopsis{i},'=');
if isempty(ind)
ind = findstr(synopsis{i},'function');
s = synopsis{i}(ind(1)+8:end);
else
s = synopsis{i}(ind(1)+1:end);
end
name{i} = strtok(s,[9:13 32 40]); % white space characters and '('
end
if length(name) == 1, name = name{1}; end
%===============================================================================
function f = fullurl(varargin)
%- Build full url from parts (using '/' and not filesep)
f = strrep(fullfile(varargin{:}),'\','/');
%===============================================================================
function str = escapeblank(str)
%- Escape white spaces using '\'
str = deblank(fliplr(deblank(fliplr(str))));
str = strrep(str,' ','\ ');
%===============================================================================
function str = entity(str)
%- Escape HTML special characters
%- See http://www.w3.org/TR/html4/charset.html#h-5.3.2
str = strrep(str,'&','&');
str = strrep(str,'<','<');
str = strrep(str,'>','>');
str = strrep(str,'"','"');
%===============================================================================
function str = horztab(str,n)
%- For browsers, the horizontal tab character is the smallest non-zero
%- number of spaces necessary to line characters up along tab stops that are
%- every 8 characters: behaviour obtained when n = 0.
if n > 0
str = strrep(str,sprintf('\t'),blanks(n));
end
|
github
|
3arbouch/PersonDetection-master
|
doxysearch.m
|
.m
|
PersonDetection-master/Source/toolbox/external/m2html/private/doxysearch.m
| 7,724 |
utf_8
|
8331cde8495f34b86aef8c18656b37f2
|
function result = doxysearch(query,filename)
%DOXYSEARCH Search a query in a 'search.idx' file
% RESULT = DOXYSEARCH(QUERY,FILENAME) looks for request QUERY
% in FILENAME (Doxygen search.idx format) and returns a list of
% files responding to the request in RESULT.
%
% See also DOXYREAD, DOXYWRITE
% Copyright (C) 2004 Guillaume Flandin <[email protected]>
% $Revision: 1.1 $Date: 2004/05/05 14:33:55 $
% 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 2
% 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, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to <[email protected]>
% See <http://www.doxygen.org/> for more details.
error(nargchk(1,2,nargin));
if nargin == 1,
filename = 'search.idx';
end
%- Open the search index file
[fid, errmsg] = fopen(filename,'r','ieee-be');
if fid == -1, error(errmsg); end
%- 4 byte header (DOXS)
header = char(fread(fid,4,'uchar'))';
if ~all(header == 'DOXS')
error('[doxysearch] Header of index file is invalid!');
end
%- many thanks to <doxyread.m> and <doxysearch.php>
r = query;
requiredWords = {};
forbiddenWords = {};
foundWords = {};
res = {};
while 1
% extract each word of the query
[t,r] = strtok(r);
if isempty(t), break, end;
if t(1) == '+'
t = t(2:end); requiredWords{end+1} = t;
elseif t(1) == '-'
t = t(2:end); forbiddenWords{end+1} = t;
end
if ~ismember(t,foundWords)
foundWords{end+1} = t;
res = searchAgain(fid,t,res);
end
end
%- Filter and sort results
docs = combineResults(res);
filtdocs = filterResults(docs,requiredWords,forbiddenWords);
filtdocs = normalizeResults(filtdocs);
res = sortResults(filtdocs);
%-
if nargout
result = res;
else
for i=1:size(res,1)
fprintf(' %d. %s - %s\n ',i,res{i,1},res{i,2});
for j=1:size(res{i,4},1)
fprintf('%s ',res{i,4}{j,1});
end
fprintf('\n');
end
end
%- Close the search index file
fclose(fid);
%===========================================================================
function res = searchAgain(fid, word,res)
i = computeIndex(word);
if i > 0
fseek(fid,i*4+4,'bof'); % 4 bytes per entry, skip header
start = size(res,1);
idx = readInt(fid);
if idx > 0
fseek(fid,idx,'bof');
statw = readString(fid);
while ~isempty(statw)
statidx = readInt(fid);
if length(statw) >= length(word) & ...
strcmp(statw(1:length(word)),word)
res{end+1,1} = statw; % word
res{end,2} = word; % match
res{end,3} = statidx; % index
res{end,4} = (length(statw) == length(word)); % full
res{end,5} = {}; % doc
end
statw = readString(fid);
end
totalfreq = 0;
for j=start+1:size(res,1)
fseek(fid,res{j,3},'bof');
numdoc = readInt(fid);
docinfo = {};
for m=1:numdoc
docinfo{m,1} = readInt(fid); % idx
docinfo{m,2} = readInt(fid); % freq
docinfo{m,3} = 0; % rank
totalfreq = totalfreq + docinfo{m,2};
if res{j,2},
totalfreq = totalfreq + docinfo{m,2};
end;
end
for m=1:numdoc
fseek(fid, docinfo{m,1}, 'bof');
docinfo{m,4} = readString(fid); % name
docinfo{m,5} = readString(fid); % url
end
res{j,5} = docinfo;
end
for j=start+1:size(res,1)
for m=1:size(res{j,5},1)
res{j,5}{m,3} = res{j,5}{m,2} / totalfreq;
end
end
end % if idx > 0
end % if i > 0
%===========================================================================
function docs = combineResults(result)
docs = {};
for i=1:size(result,1)
for j=1:size(result{i,5},1)
key = result{i,5}{j,5};
rank = result{i,5}{j,3};
if ~isempty(docs) & ismember(key,{docs{:,1}})
l = find(ismember({docs{:,1}},key));
docs{l,3} = docs{l,3} + rank;
docs{l,3} = 2 * docs{l,3};
else
l = size(docs,1)+1;
docs{l,1} = key; % key
docs{l,2} = result{i,5}{j,4}; % name
docs{l,3} = rank; % rank
docs{l,4} = {}; %words
end
n = size(docs{l,4},1);
docs{l,4}{n+1,1} = result{i,1}; % word
docs{l,4}{n+1,2} = result{i,2}; % match
docs{l,4}{n+1,3} = result{i,5}{j,2}; % freq
end
end
%===========================================================================
function filtdocs = filterResults(docs,requiredWords,forbiddenWords)
filtdocs = {};
for i=1:size(docs,1)
words = docs{i,4};
c = 1;
j = size(words,1);
% check required
if ~isempty(requiredWords)
found = 0;
for k=1:j
if ismember(words{k,1},requiredWords)
found = 1;
break;
end
end
if ~found, c = 0; end
end
% check forbidden
if ~isempty(forbiddenWords)
for k=1:j
if ismember(words{k,1},forbiddenWords)
c = 0;
break;
end
end
end
% keep it or not
if c,
l = size(filtdocs,1)+1;
filtdocs{l,1} = docs{i,1};
filtdocs{l,2} = docs{i,2};
filtdocs{l,3} = docs{i,3};
filtdocs{l,4} = docs{i,4};
end;
end
%===========================================================================
function docs = normalizeResults(docs);
m = max([docs{:,3}]);
for i=1:size(docs,1)
docs{i,3} = 100 * docs{i,3} / m;
end
%===========================================================================
function result = sortResults(docs);
[y, ind] = sort([docs{:,3}]);
result = {};
ind = fliplr(ind);
for i=1:size(docs,1)
result{i,1} = docs{ind(i),1};
result{i,2} = docs{ind(i),2};
result{i,3} = docs{ind(i),3};
result{i,4} = docs{ind(i),4};
end
%===========================================================================
function i = computeIndex(word)
if length(word) < 2,
i = -1;
else
i = double(word(1)) * 256 + double(word(2));
end
%===========================================================================
function s = readString(fid)
s = '';
while 1
w = fread(fid,1,'uchar');
if w == 0, break; end
s(end+1) = char(w);
end
%===========================================================================
function i = readInt(fid)
i = fread(fid,1,'uint32');
|
github
|
3arbouch/PersonDetection-master
|
doxywrite.m
|
.m
|
PersonDetection-master/Source/toolbox/external/m2html/private/doxywrite.m
| 3,584 |
utf_8
|
3255d8f824957ebc173dde374d0f78af
|
function doxywrite(filename, kw, statinfo, docinfo)
%DOXYWRITE Write a 'search.idx' file compatible with DOXYGEN
% DOXYWRITE(FILENAME, KW, STATINFO, DOCINFO) writes file FILENAME
% (Doxygen search.idx. format) using the cell array KW containing the
% word list, the sparse matrix (nbword x nbfile) with non-null values
% in (i,j) indicating the frequency of occurence of word i in file j
% and the cell array (nbfile x 2) containing the list of urls and names
% of each file.
%
% See also DOXYREAD
% Copyright (C) 2003 Guillaume Flandin <[email protected]>
% $Revision: 1.0 $Date: 2003/23/10 15:52:56 $
% 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 2
% 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, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to <[email protected]>
% See <http://www.doxygen.org/> for more details.
error(nargchk(4,4,nargin));
%- Open the search index file
[fid, errmsg] = fopen(filename,'w','ieee-be');
if fid == -1, error(errmsg); end
%- Write 4 byte header (DOXS)
fwrite(fid,'DOXS','uchar');
pos = ftell(fid);
%- Write 256 * 256 header
idx = zeros(256);
writeInt(fid, idx);
%- Write word lists
i = 1;
idx2 = zeros(1,length(kw));
while 1
s = kw{i}(1:2);
idx(double(s(2)+1), double(s(1)+1)) = ftell(fid);
while i <= length(kw) & strmatch(s, kw{i})
writeString(fid,kw{i});
idx2(i) = ftell(fid);
writeInt(fid,0);
i = i + 1;
end
fwrite(fid, 0, 'int8');
if i > length(kw), break; end
end
%- Write extra padding bytes
pad = mod(4 - mod(ftell(fid),4), 4);
for i=1:pad, fwrite(fid,0,'int8'); end
pos2 = ftell(fid);
%- Write 256*256 header again
fseek(fid, pos, 'bof');
writeInt(fid, idx);
% Write word statistics
fseek(fid,pos2,'bof');
idx3 = zeros(1,length(kw));
for i=1:length(kw)
idx3(i) = ftell(fid);
[ia, ib, v] = find(statinfo(i,:));
counter = length(ia); % counter
writeInt(fid,counter);
for j=1:counter
writeInt(fid,ib(j)); % index
writeInt(fid,v(j)); % freq
end
end
pos3 = ftell(fid);
%- Set correct handles to keywords
for i=1:length(kw)
fseek(fid,idx2(i),'bof');
writeInt(fid,idx3(i));
end
% Write urls
fseek(fid,pos3,'bof');
idx4 = zeros(1,length(docinfo));
for i=1:length(docinfo)
idx4(i) = ftell(fid);
writeString(fid, docinfo{i,1}); % name
writeString(fid, docinfo{i,2}); % url
end
%- Set corrext handles to word statistics
fseek(fid,pos2,'bof');
for i=1:length(kw)
[ia, ib, v] = find(statinfo(i,:));
counter = length(ia);
fseek(fid,4,'cof'); % counter
for m=1:counter
writeInt(fid,idx4(ib(m)));% index
fseek(fid,4,'cof'); % freq
end
end
%- Close the search index file
fclose(fid);
%===========================================================================
function writeString(fid, s)
fwrite(fid,s,'uchar');
fwrite(fid,0,'int8');
%===========================================================================
function writeInt(fid, i)
fwrite(fid,i,'uint32');
|
github
|
3arbouch/PersonDetection-master
|
doxyread.m
|
.m
|
PersonDetection-master/Source/toolbox/external/m2html/private/doxyread.m
| 3,093 |
utf_8
|
3152e7d26bf7ac64118be56f72832a20
|
function [statlist, docinfo] = doxyread(filename)
%DOXYREAD Read a 'search.idx' file generated by DOXYGEN
% STATLIST = DOXYREAD(FILENAME) reads FILENAME (Doxygen search.idx
% format) and returns the list of keywords STATLIST as a cell array.
% [STATLIST, DOCINFO] = DOXYREAD(FILENAME) also returns a cell array
% containing details for each keyword (frequency in each file where it
% appears and the URL).
%
% See also DOXYSEARCH, DOXYWRITE
% Copyright (C) 2003 Guillaume Flandin <[email protected]>
% $Revision: 1.0 $Date: 2003/05/10 17:41:21 $
% 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 2
% 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, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to <[email protected]>
% See <http://www.doxygen.org/> for more details.
error(nargchk(0,1,nargin));
if nargin == 0,
filename = 'search.idx';
end
%- Open the search index file
[fid, errmsg] = fopen(filename,'r','ieee-be');
if fid == -1, error(errmsg); end
%- 4 byte header (DOXS)
header = char(fread(fid,4,'uchar'))';
%- 256*256*4 byte index
idx = fread(fid,256*256,'uint32');
idx = reshape(idx,256,256);
%- Extract list of words
i = find(idx);
statlist = cell(0,2);
for j=1:length(i)
fseek(fid, idx(i(j)), 'bof');
statw = readString(fid);
while ~isempty(statw)
statidx = readInt(fid);
statlist{end+1,1} = statw; % word
statlist{end,2} = statidx; % index
statw = readString(fid);
end
end
%- Extract occurence frequency of each word and docs info (name and url)
docinfo = cell(size(statlist,1),1);
for k=1:size(statlist,1)
fseek(fid, statlist{k,2}, 'bof');
numdoc = readInt(fid);
docinfo{k} = cell(numdoc,4);
for m=1:numdoc
docinfo{k}{m,1} = readInt(fid); % idx
docinfo{k}{m,2} = readInt(fid); % freq
end
for m=1:numdoc
fseek(fid, docinfo{k}{m,1}, 'bof');
docinfo{k}{m,3} = readString(fid); % name
docinfo{k}{m,4} = readString(fid); % url
end
docinfo{k} = reshape({docinfo{k}{:,2:4}},numdoc,[]);
end
%- Close the search index file
fclose(fid);
%- Remove indexes
statlist = {statlist{:,1}}';
%===========================================================================
function s = readString(fid)
s = '';
while 1
w = fread(fid,1,'uchar');
if w == 0, break; end
s(end+1) = char(w);
end
%===========================================================================
function i = readInt(fid)
i = fread(fid,1,'uint32');
|
github
|
3arbouch/PersonDetection-master
|
imwrite2split.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/imwrite2split.m
| 1,617 |
utf_8
|
4222fd45df123e6dec9ef40ae793004f
|
% Writes/reads a large set of images into/from multiple directories.
%
% This is useful since certain OS handle very large directories (of say
% >20K images) rather poorly (I'm talking to you Bill). Thus, can take
% 100K images, and write into 5 separate directories, then read them back
% in.
%
% USAGE
% I = imwrite2split( I, nSplits, spliti, path, [varargin] )
%
% INPUTS
% I - image or images (if [] reads else writes)
% nSplits - number of directories to split data into
% spliti - first split number
% path - directory where images are
% writePrms - [varargin] parameters to imwrite2
%
% OUTPUTS
% I - image or images (read from disk if input I=[])
%
% EXAMPLE
% load images; clear IDXi IDXv t video videos;
% imwrite2split( images(:,:,1:10), 2, 0, 'rats', 'rats', 'png', 5 );
% images2=imwrite2split( [], 2, 0, 'rats', 'rats', 'png', 5 );
%
% See also IMWRITE2
% Piotr's Image&Video Toolbox Version NEW
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function I = imwrite2split( I, nSplits, spliti, path, varargin )
n = size(I,3); if( isempty(I) ); n=0; end
nSplits = min(n,nSplits);
for s=1:nSplits
pathSplit = [path int2str2(s-1+spliti,2)];
if( n>0 ) % write
nPerDir = ceil( n / nSplits );
ISplit = I(:,:,1:min(end,nPerDir));
imwrite2( ISplit, nPerDir>1, 0, pathSplit, varargin{:} );
if( s~=nSplits ); I = I(:,:,(nPerDir+1):end); end
else % read
ISplit = imwrite2( [], 1, 0, pathSplit, varargin{:} );
I = cat(3,I,ISplit);
end
end
|
github
|
3arbouch/PersonDetection-master
|
playmovies.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/playmovies.m
| 1,935 |
utf_8
|
ef2eaad8a130936a1a281f1277ca0ea1
|
% [4D] shows R videos simultaneously as a movie.
%
% Plays a movie.
%
% USAGE
% playmovies( I, [fps], [loop] )
%
% INPUTS
% I - MxNxTxR or MxNx1xTxR or MxNx3xTxR array (if MxNxT calls
% playmovie)
% fps - [100] maximum number of frames to display per second use
% fps==0 to introduce no pause and have the movie play as
% fast as possible
% loop - [0] number of time to loop video (may be inf),
% if neg plays video forward then backward then forward etc.
%
% OUTPUTS
%
% EXAMPLE
% load( 'images.mat' );
% playmovies( videos );
%
% See also MONTAGES, PLAYMOVIE, MAKEMOVIES
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function playmovies( I, fps, loop )
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n PLAYMOVIE is its '...
'recommended replacement.'],upper(mfilename));
if( nargin<2 || isempty(fps)); fps = 100; end
if( nargin<3 || isempty(loop)); loop = 1; end
playmovie( I, fps, loop )
%
% nd=ndims(I); siz=size(I); nframes=siz(end-1);
% if( nd==3 ); playmovie( I, fps, loop ); return; end
% if( iscell(I) ); error('cell arrays not supported.'); end
% if( ~(nd==4 || (nd==5 && any(size(I,3)==[1 3]))) )
% error('unsupported dimension of I'); end
% inds={':'}; inds=inds(:,ones(1,nd-2));
% clim = [min(I(:)),max(I(:))];
%
% h=gcf; colormap gray; figure(h); % bring to focus
% for nplayed = 1 : abs(loop)
% if( loop<0 && mod(nplayed,2)==1 )
% order = nframes:-1:1;
% else
% order = 1:nframes;
% end
% for i=order
% tic; try disc=get(h); catch return; end %#ok<NASGU>
% montage2(squeeze(I(inds{:},i,:)),1,[],clim);
% title(sprintf('frame %d of %d',i,nframes));
% if(fps>0); pause(1/fps - toc); else pause(eps); end
% end
% end
|
github
|
3arbouch/PersonDetection-master
|
pca_apply_large.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/pca_apply_large.m
| 2,062 |
utf_8
|
af84a2179b9d8042519bc6b378736a88
|
% Wrapper for pca_apply that allows for application to large X.
%
% Wrapper for pca_apply that splits and processes X in parts, this may be
% useful if processing cannot be done fully in parallel because of memory
% constraints. See pca_apply for usage.
%
% USAGE
% same as pca_apply
%
% INPUTS
% same as pca_apply
%
% OUTPUTS
% same as pca_apply
%
% EXAMPLE
%
% See also PCA, PCA_APPLY, PCA_VISUALIZE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function [ Yk, Xhat, avsq ] = pca_apply_large( X, U, mu, vars, k )
siz = size(X); nd = ndims(X); [N,r] = size(U);
if(N==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
inds = {':'}; inds = inds(:,ones(1,nd-1));
d= prod(siz(1:end-1));
% some error checking
if(d~=N); error('incorrect size for X or U'); end
if(isa(X,'uint8')); X = double(X); end
if( k>r )
warning(['Only ' int2str(r) '<k comp. available.']); %#ok<WNTAG>
k=r;
end
% Will run out of memory if X has too many elements. Hence, run
% pca_apply on parts of X and recombine.
maxwidth = ceil( (10^7) / d );
if(maxwidth > siz(end))
if (nargout==1)
Yk = pca_apply( X, U, mu, vars, k );
elseif (nargout==2)
[Yk, Xhat] = pca_apply( X, U, mu, vars, k );
else
[ Yk, Xhat, avsq ] = pca_apply( X, U, mu, vars, k );
end
else
Yk = zeros( k, siz(end) ); Xhat = zeros( siz );
avsq = 0; avsqOrig = 0; last = 0;
while(last < siz(end))
first=last+1; last=min(first+maxwidth-1,siz(end));
Xi = X(inds{:}, first:last);
if( nargout==1 )
Yki = pca_apply( Xi, U, mu, vars, k );
else
if( nargout==2 )
[Yki,Xhati] = pca_apply( Xi, U, mu, vars, k );
else
[Yki,Xhati,avsqi,avsqOrigi] = pca_apply( Xi, U, mu, vars, k );
avsq = avsq + avsqi; avsqOrig = avsqOrig + avsqOrigi;
end;
Xhat(inds{:}, first:last ) = Xhati;
end
Yk( :, first:last ) = Yki;
end;
if( nargout==3); avsq = avsq / avsqOrig; end
end
|
github
|
3arbouch/PersonDetection-master
|
montages2.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/montages2.m
| 2,269 |
utf_8
|
505e2be915d65fff8bfef8473875cc98
|
% MONTAGES2 [4D] Used to display R sets of T images each.
%
% Displays one montage (see montage2) per row. Each of the R image sets is
% flattened to a single long image by concatenating the T images in the
% set. Alternative to montages.
%
% USAGE
% varargout = montages2( IS, [montage2prms], [padSiz] )
%
% INPUTS
% IS - MxNxTxR or MxNx1xTxR or MxNx3xTxR array
% montage2prms - [] params for montage2; ex: {showLns,extraInf}
% padSiz - [4] total amount of vertical or horizontal padding
%
% OUTPUTS
% I - 3D or 4D array of flattened images, disp with montage2
% mm - #montages/row
% nn - #montages/col
%
% EXAMPLE
% load( 'images.mat' );
% imageclusters = clustermontage( images, IDXi, 16, 1 );
% montages2( imageclusters );
%
% See also MONTAGES, MAKEMOVIES, MONTAGE2, CLUSTERMONTAGE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function varargout = montages2( IS, montage2prms, padSiz )
if( nargin<2 || isempty(montage2prms) ); montage2prms = {}; end
if( nargin<3 || isempty(padSiz) ); padSiz = 4; end
[padSiz,er] = checknumericargs( padSiz,[1 1], 0, 1 ); error(er);
% get/test image format info
nd = ndims(IS); siz = size(IS);
if( nd==5 ) %MxNx1xTxR or MxNx3xTxR
nch = size(IS,3);
if( nch~=1 && nch~=3 ); error('illegal image stack format'); end
if( nch==1 ); IS = squeeze(IS); nd=4; siz=size(IS); end
end
if ~any(nd==3:5)
error('unsupported dimension of IS');
end
% reshape IS so that each 3D element is concatenated to a 2D image, adding
% padding
padEl = max(IS(:));
IS=arraycrop2dims(IS, [siz(1)+padSiz siz(2:end)], padEl ); %UD pad
siz=size(IS);
if(nd==3) % reshape bw single
IS=squeeze( reshape( IS, siz(1), [] ) );
elseif(nd==4) % reshape bw
IS=squeeze( reshape( IS, siz(1), [], siz(4) ) );
else % reshape color
IS=squeeze( reshape(permute(IS,[1 2 4 3 5]),siz(1),[],siz(3),siz(5)));
end; siz = size(IS);
IS=arraycrop2dims(IS, [siz(1) siz(2)+padSiz siz(3:end)], padEl);
% show using montage2
varargout = cell(1,nargout);
if( nargout); varargout{1}=IS; end;
[varargout{2:end}] = montage2( IS, montage2prms{:} );
title(inputname(1));
|
github
|
3arbouch/PersonDetection-master
|
filter_gauss_1D.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/filter_gauss_1D.m
| 1,137 |
utf_8
|
94a453b82dcdeba67bd886e042d552d9
|
% 1D Gaussian filter.
%
% Equivalent to (but faster then):
% f = fspecial('Gaussian',[2*r+1,1],sigma);
% f = filter_gauss_nD( 2*r+1, r+1, sigma^2 );
%
% USAGE
% f = filter_gauss_1D( r, sigma, [show] )
%
% INPUTS
% r - filter size=2r+1, if r=[] -> r=ceil(2.25*sigma)
% sigma - standard deviation of filter
% show - [0] figure to use for optional display
%
% OUTPUTS
% f - 1D Gaussian filter
%
% EXAMPLE
% f1 = filter_gauss_1D( 10, 2, 1 );
% f2 = filter_gauss_nD( 21, [], 2^2, 2);
%
% See also FILTER_BINOMIAL_1D, FILTER_GAUSS_ND, FSPECIAL
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function f = filter_gauss_1D( r, sigma, show )
if( nargin<3 || isempty(show) ); show=0; end
if( isempty(r) ); r = ceil(sigma*2.25); end
if( mod(r,1)~=0 ); error( 'r must be an integer'); end
% compute filter
x = -r:r;
f = exp(-(x.*x)/(2*sigma*sigma))';
f(f<eps*max(f(:))*10) = 0;
sumf = sum(f(:)); if(sumf~=0); f = f/sumf; end
% display
if(show); filter_visualize_1D( f, show ); end
|
github
|
3arbouch/PersonDetection-master
|
clfEcoc.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/clfEcoc.m
| 1,493 |
utf_8
|
e77e1b4fd5469ed39f47dd6ed15f130f
|
function clf = clfEcoc(p,clfInit,clfparams,nclasses,use01targets)
% Wrapper for ecoc that makes ecoc compatible with nfoldxval.
%
% Requires the SVM toolbox by Anton Schwaighofer.
%
% USAGE
% clf = clfEcoc(p,clfInit,clfparams,nclasses,use01targets)
%
% INPUTS
% p - data dimension
% clfInit - binary classifier init (see nfoldxval)
% clfparams - binary classifier parameters (see nfoldxval)
% nclasses - num of classes (currently 3<=nclasses<=7 suppored)
% use01targets - see ecoc
%
% OUTPUTS
% clf - see ecoc
%
% EXAMPLE
%
% See also ECOC, NFOLDXVAL, CLFECOCCODE
%
% Piotr's Image&Video Toolbox Version 2.0
% Copyright 2008 Piotr Dollar. [pdollar-at-caltech.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Lesser GPL [see external/lgpl.txt]
if( nclasses<3 || nclasses>7 )
error( 'currently only works if 3<=nclasses<=7'); end;
if( nargin<5 || isempty(use01targets)); use01targets=0; end;
% create code (limited for now)
[C,nbits] = clfEcocCode( nclasses );
clf = ecoc(nclasses, nbits, C, use01targets ); % didn't use to pass use01?
clf.verbosity = 0; % don't diplay output
% initialize and temporarily store binary learner
clf.templearner = feval( clfInit, p, clfparams{:} );
% ecoctrain2 is custom version of ecoctrain
clf.funTrain = @clfEcocTrain;
clf.funFwd = @ecocfwd;
function clf = clfEcocTrain( clf, varargin )
clf = ecoctrain( clf, clf.templearner, varargin{:} );
|
github
|
3arbouch/PersonDetection-master
|
getargs.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/getargs.m
| 3,455 |
utf_8
|
de2bab917fa6b9ba3099f1c6b6d68cf0
|
% Utility to process parameter name/value pairs.
%
% DEPRECATED -- ONLY USED BY KMEANS2? SHOULD BE REMOVED.
% USE GETPARAMDEFAULTS INSTEAD.
%
% Based on code fromt Matlab Statistics Toolobox's "private/statgetargs.m"
%
% [EMSG,A,B,...]=GETARGS(PNAMES,DFLTS,'NAME1',VAL1,'NAME2',VAL2,...)
% accepts a cell array PNAMES of valid parameter names, a cell array DFLTS
% of default values for the parameters named in PNAMES, and additional
% parameter name/value pairs. Returns parameter values A,B,... in the same
% order as the names in PNAMES. Outputs corresponding to entries in PNAMES
% that are not specified in the name/value pairs are set to the
% corresponding value from DFLTS. If nargout is equal to length(PNAMES)+1,
% then unrecognized name/value pairs are an error. If nargout is equal to
% length(PNAMES)+2, then all unrecognized name/value pairs are returned in
% a single cell array following any other outputs.
%
% EMSG is empty if the arguments are valid, or the text of an error message
% if an error occurs. GETARGS does not actually throw any errors, but
% rather returns an error message so that the caller may throw the error.
% Outputs will be partially processed after an error occurs.
%
% USAGE
% [emsg,varargout]=getargs(pnames,dflts,varargin)
%
% INPUTS
% pnames - cell of valid parameter names
% dflts - cell of default parameter values
% varargin - list of proposed name / value pairs
%
% OUTPUTS
% emsg - error msg - '' if no error
% varargout - list of assigned name / value pairs
%
% EXAMPLE
% pnames = {'color' 'linestyle', 'linewidth'}; dflts = { 'r','_','1'};
% v = {'linew' 2 'nonesuch' [1 2 3] 'linestyle' ':'};
% [emsg,color,linestyle,linewidth,unrec] = getargs(pnames,dflts,v{:}) % ok
% [emsg,color,linestyle,linewidth] = getargs(pnames,dflts,v{:}) % err
%
% See also GETPARAMDEFAULTS
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function [emsg,varargout]=getargs(pnames,dflts,varargin)
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n It will be ' ...
'removed in the next version of the toolbox.'],upper(mfilename));
% We always create (nparams+1) outputs:
% one for emsg
% nparams varargs for values corresponding to names in pnames
% If they ask for one more (nargout == nparams+2), it's for unrecognized
% names/values
emsg = '';
nparams = length(pnames);
varargout = dflts;
unrecog = {};
nargs = length(varargin);
% Must have name/value pairs
if mod(nargs,2)~=0
emsg = sprintf('Wrong number of arguments.');
else
% Process name/value pairs
for j=1:2:nargs
pname = varargin{j};
if ~ischar(pname)
emsg = sprintf('Parameter name must be text.');
break;
end
i = strmatch(lower(pname),lower(pnames));
if isempty(i)
% if they've asked to get back unrecognized names/values, add this
% one to the list
if nargout > nparams+1
unrecog((end+1):(end+2)) = {varargin{j} varargin{j+1}};
% otherwise, it's an error
else
emsg = sprintf('Invalid parameter name: %s.',pname);
break;
end
elseif length(i)>1
emsg = sprintf('Ambiguous parameter name: %s.',pname);
break;
else
varargout{i} = varargin{j+1};
end
end
end
varargout{nparams+1} = unrecog;
|
github
|
3arbouch/PersonDetection-master
|
normxcorrn_fg.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/normxcorrn_fg.m
| 2,699 |
utf_8
|
e65c38d97efb3a624e0fa94a97f75eb6
|
% Normalized n-dimensional cross-correlation with a mask.
%
% Similar to normxcorrn, except takes an additional argument that specifies
% a figure ground mask for the T. That is T_fg must be of the same
% dimensions as T, with each entry being 0 or 1, where zero specifies
% regions to ignore (the ground) and 1 specifies interesting regions (the
% figure). Essentially T_fg specifies regions in T that are interesting
% and should be taken into account when doing normalized cross correlation.
% This allows for templates of arbitrary shape, and not just squares.
%
% Note: this function is approximately 3 times slower then normxcorr2
% because it cannot use the trick of precomputing sums.
%
% USAGE
% C = normxcorrn_fg( T, T_fg, A, [shape] )
%
% INPUTS
% T - template to correlate to each window in A
% T_fg - figure/ground mask for the template
% A - matrix to correlate T to
% shape - ['full'] 'valid', 'full', or 'same', see convn_fast help
%
% OUTPUTS
% C - correlation matrix
%
% EXAMPLE
% A=rand(50); B=rand(11); Bfg=ones(11);
% C1=normxcorrn_fg(B,Bfg,A); C2=normxcorr2(B,A);
% figure(1); im(C1); figure(2); im(C2);
% figure(3); im(abs(C1-C2));
%
% See also NORMXCORRN
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function C = normxcorrn_fg( T, T_fg, A, shape )
if( nargin <4 || isempty(shape)); shape='full'; end;
if( ndims(T)~=ndims(A) || ndims(T)~=ndims(T_fg) )
error('TEMPALTE, T_fg, and A must have same number of dimensions'); end;
if( any(size(T)~=size(T_fg)))
error('TEMPALTE and T_fg must have same dimensions'); end;
if( ~all(T_fg==0 | T_fg==1))
error('T_fg may have only entries either 0 or 1'); end;
nkeep = sum(T_fg(:));
if( nkeep==0); error('T_fg must have some nonzero values'); end;
% center T on 0 and normalize magnitued to 1, excluding ground
% T= (T-T_av) / ||(T-T_av)||
T(T_fg==0)=0;
T = T - sum(T(:)) / nkeep;
T(T_fg==0)=0;
T = T / norm( T(:) );
% flip for convn_fast purposes
for d=1:ndims(T); T = flipdim(T,d); end;
for d=1:ndims(T_fg); T_fg = flipdim(T_fg,d); end;
% get average over each window over A
A_av = convn_fast( A, T_fg/nkeep, shape );
% get magnitude over each window over A "mag(WA-WAav)"
% We can rewrite the above as "sqrt(SUM(WAi^2)-n*WAav^2)". so:
A_mag = convn_fast( A.*A, T_fg, shape ) - nkeep * A_av .* A_av;
A_mag = sqrt(A_mag); A_mag(A_mag<.000001)=1; %removes divide by 0 error
% finally get C. in each image window, we will now do:
% "dot(T,(WA-WAav)) / mag(WA-WAav)"
C = convn_fast(A,T,shape) - A_av*sum(T(:));
C = C ./ A_mag;
|
github
|
3arbouch/PersonDetection-master
|
makemovie.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/makemovie.m
| 1,266 |
utf_8
|
9a03d9a5227c4eaa86520f206ce283e7
|
% [3D] Used to convert a stack of T images into a movie.
%
% To display same data statically use montage.
%
% USAGE
% M = makemovies( IS )
%
% INPUTS
% IS - MxNxT or MxNx1xT or MxNx3xT array of movies.
%
% OUTPUTS
% M - resulting movie
%
% EXAMPLE
% load( 'images.mat' );
% M = makemovie( videos(:,:,:,1) );
% movie( M );
%
% See also MONTAGE2, MAKEMOVIES, PLAYMOVIE, CELL2ARRAY, FEVALARRAYS,
% IMMOVIE, MOVIE2AVI
% Piotr's Image&Video Toolbox Version NEW
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function M = makemovie( IS )
% get images format (if image stack is MxNxT convert to MxNx1xT)
if (ndims(IS)==3); IS = permute(IS, [1,2,4,3] ); end
siz = size(IS); nch = siz(3); nd = ndims(IS);
if ( nd~=4 ); error('unsupported dimension of IS'); end
if( nch~=1 && nch~=3 ); error('illegal image stack format'); end;
% normalize for maximum contrast
if( isa(IS,'double') ); IS = IS - min(IS(:)); IS = IS / max(IS(:)); end
% make movie
for i=1:siz(4)
Ii=IS(:,:,:,i);
if( nch==1 ); [Ii,Mi] = gray2ind( Ii ); else Mi=[]; end
if i==1
M=repmat(im2frame( Ii, Mi ),[1,siz(4)]);
else
M(i) = im2frame( Ii, Mi );
end
end
|
github
|
3arbouch/PersonDetection-master
|
localsum_block.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/localsum_block.m
| 815 |
utf_8
|
1216b03a3bd44ff1fc3256de16a2f1c6
|
% Calculates the sum in non-overlapping blocks of I of size dims.
%
% Similar to localsum except gets sum in non-overlapping windows.
% Equivalent to doing localsum, and then subsampling (except more
% efficient).
%
% USAGE
% I = localsum_block( I, dims )
%
% INPUTS
% I - matrix to compute sum over
% dims - size of volume to compute sum over
%
% OUTPUTS
% I - resulting array
%
% EXAMPLE
% load trees; I=ind2gray(X,map);
% I2 = localsum_block( I, 11 );
% figure(1); im(I); figure(2); im(I2);
%
% See also LOCALSUM
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function I = localsum_block( I, dims )
I = nlfiltblock_sep( I, dims, @rnlfiltblock_sum );
|
github
|
3arbouch/PersonDetection-master
|
imrotate2.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/imrotate2.m
| 1,326 |
utf_8
|
bb2ff6c3138ce5f53154d58d7ebc4f31
|
% Custom version of imrotate that demonstrates use of apply_homography.
%
% Works exactly the same as imrotate. For usage see imrotate.
%
% USAGE
% IR = imrotate2( I, angle, [method], [bbox] )
%
% INPUTS
% I - 2D image [converted to double]
% angle - angle to rotate in degrees
% method - ['linear'] 'nearest', 'linear', 'spline', 'cubic'
% bbox - ['loose'] 'loose' or 'crop'
%
% OUTPUTS
% IR - rotated image
%
% EXAMPLE
% load trees;
% tic; X1 = imrotate( X, 55, 'bicubic' ); toc,
% tic; X2 = imrotate2( X, 55, 'bicubic' ); toc
% clf; subplot(2,2,1); im(X); subplot(2,2,2); im(X1-X2);
% subplot(2,2,3); im(X1); subplot(2,2,4); im(X2);
%
% See also IMROTATE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function IR = imrotate2( I, angle, method, bbox )
if( ~isa( I, 'double' ) ); I = double(I); end
if( nargin<3 || isempty(method)); method='linear'; end
if( nargin<4 || isempty(bbox) ); bbox='loose'; end
if( strcmp(method,'bilinear') || strcmp(method,'lin')); method='linear';end
% convert arguments for apply_homography
angle_rads = angle /180 * pi;
R = rotationMatrix( angle_rads );
H = [R [0;0]; 0 0 1];
IR = apply_homography( I, H, method, bbox );
|
github
|
3arbouch/PersonDetection-master
|
imSubsResize.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/imSubsResize.m
| 1,338 |
utf_8
|
cd7dedf790c015adfb1f2d620e9ed82f
|
% Resizes subs by resizVals.
%
% Resizes subs in subs/vals image representation by resizVals.
%
% This essentially replaces each sub by sub.*resizVals. The only subtlety
% is that in images the leftmost sub value is .5, so for example when
% resizing by a factor of 2, the first pixel is replaced by 2 pixels and so
% location 1 in the original image goes to location 1.5 in the second
% image, NOT 2. It may be necessary to round the values afterward.
%
% USAGE
% subs = imSubsResize( subs, resizVals, [zeroPnt] )
%
% INPUTS
% subs - subscripts of point locations (n x d)
% resizVals - k element vector of shrinking factors
% zeroPnt - [.5] See comment above.
%
% OUTPUTS
% subs - transformed subscripts of point locations (n x d)
%
% EXAMPLE
% subs = imSubsResize( [1 1; 2 2], [2 2] )
%
%
% See also IMSUBSTOARRAY
% Piotr's Image&Video Toolbox Version NEW
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function subs = imSubsResize( subs, resizVals, zeroPnt )
if( nargin<3 || isempty(zeroPnt) ); zeroPnt=.5; end
[n d] = size(subs);
[resizVals,er] = checkNumArgs( resizVals, [1 d], -1, 2 ); error(er);
% transform subs
resizVals = repmat( resizVals, [n, 1] );
subs = (subs - zeroPnt) .* resizVals + zeroPnt;
|
github
|
3arbouch/PersonDetection-master
|
imtranslate.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/imtranslate.m
| 1,183 |
utf_8
|
054727fb31c105414b655c0f938b6ced
|
% Translate an image to subpixel accuracy.
%
% Note that for subplixel accuracy cannot use nearest neighbor interp.
%
% USAGE
% IR = imtranslate( I, dx, dy, [method], [bbox] )
%
% INPUTS
% I - 2D image [converted to double]
% dx - x translation (right)
% dy - y translation (up)
% method - ['linear'] 'nearest', 'linear', 'spline', 'cubic'
% bbox - ['loose'] 'loose' or 'crop'
%
% OUTPUTS
% IR - translated image
%
% EXAMPLE
% load trees;
% XT = imtranslate(X,0,1.5,'bicubic','crop');
% figure(1); im(X,[0 255]); figure(2); im(XT,[0 255]);
%
% See also IMROTATE2
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function IR = imtranslate( I, dx, dy, method, bbox )
if( ~isa( I, 'double' ) ); I = double(I); end
if( nargin<4 || isempty(method)); method='linear'; end
if( nargin<5 || isempty(bbox) ); bbox='loose'; end
if( strcmp(method,'bilinear') || strcmp(method,'lin')); method='linear';end
% convert arguments for apply_homography
H = [eye(2) [dy; dx]; 0 0 1];
IR = apply_homography( I, H, method, bbox );
|
github
|
3arbouch/PersonDetection-master
|
randperm2.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/randperm2.m
| 1,398 |
utf_8
|
5007722f3d5f5ba7c0f83f32ef8a3a2c
|
% Returns a random permutation of integers.
%
% randperm2(n) is a random permutation of the integers from 1 to n. For
% example, randperm2(6) might be [2 4 5 6 1 3]. randperm2(n,k) is only
% returns the first k elements of the permuation, so for example
% randperm2(6) might be [2 4]. This is a faster version of randperm.m if
% only need first k<<n elements of the random permutation. Also uses less
% random bits (only k). Note that this is an implementation O(k), versus
% the matlab implementation which is O(nlogn), however, in practice it is
% often slower for k=n because it uses a loop.
%
% USAGE
% p = randperm2( n, k )
%
% INPUTS
% n - permute 1:n
% k - keep only first k outputs
%
% OUTPUTS
% p - k length vector of permutations
%
% EXAMPLE
% randperm2(10,5)
%
% See also RANDPERM
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function p = randperm2( n, k )
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n RANDSAMPLE is its '...
'recommended replacement.'],upper(mfilename));
p = randsample( n, k );
%if (nargin<2); k=n; else k = min(k,n); end
% p = 1:n;
% for i=1:k
% r = i + floor( (n-i+1)*rand );
% t = p(r); p(r) = p(i); p(i) = t;
% end
% p = p(1:k);
|
github
|
3arbouch/PersonDetection-master
|
apply_homography.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/apply_homography.m
| 3,582 |
utf_8
|
9c3ed72d35b1145f41114e6e6135b44f
|
% Applies the homography defined by H on the image I.
%
% Takes the center of the image as the origin, not the top left corner.
% Also, the coordinate system is row/ column format, so H must be also.
%
% The bounding box of the image is set by the BBOX argument, a string that
% can be 'loose' (default) or 'crop'. When BBOX is 'loose', IR includes the
% whole transformed image, which generally is larger than I. When BBOX is
% 'crop' IR is cropped to include only the central portion of the
% transformed image and is the same size as I. Preserves I's type.
%
% USAGE
% IR = apply_homography( I, H, [method], [bbox], [show] )
%
% INPUTS
% I - input black and white image (2D double or unint8 array)
% H - 3x3 nonsingular homography matrix
% method - ['linear'] for interp2 'nearest','linear','spline','cubic'
% bbox - ['loose'] see above for meaning of bbox 'loose','crop')
% show - [0] figure to use for optional display
%
% OUTPUTS
% IR - result of applying H to I.
%
% EXAMPLE
% load trees; I=X;
% R = rotationMatrix( pi/4 ); T = [1; 3]; H = [R T; 0 0 1];
% IR = apply_homography( I, H, [], 'crop', 1 );
%
% See also TEXTURE_MAP, IMROTATE2
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function IR = apply_homography( I, H, method, bbox, show )
if( ndims(I)~=2 ); error('I must a MxN array'); end;
if(any(size(H)~=[3 3])); error('H must be 3 by 3'); end;
if(rank(H)~=3); error('H must be full rank.'); end;
if( nargin<3 || isempty(method)); method='linear'; end;
if( nargin<4 || isempty(bbox)); bbox='loose'; end;
if( nargin<5 || isempty(show)); show=0; end;
classname = class( I );
if(~strcmp(classname,'double')); I = double(I); end
I = padarray(I,[3,3],eps,'both');
siz = size(I);
% set origin to be center of image
rstart = (-siz(1)+1)/2; rend = (siz(1)-1)/2;
cstart = (-siz(2)+1)/2; cend = (siz(2)-1)/2;
% If 'bbox' then get bounds of resulting image. To do this project the
% original points accoring to the homography and see the bounds. Note
% that since a homography maps a quadrilateral to a quadrilateral only
% need to look at where the bounds of the quadrilateral are mapped to.
% If 'same' then simply use the original image bounds.
if (strcmp(bbox,'loose'))
pr = H * [rstart rend rstart rend; cstart cstart cend cend; 1 1 1 1];
row_dest = pr(1,:) ./ pr(3,:); col_dest = pr(2,:) ./ pr(3,:);
minr = floor(min(row_dest(:))); maxr = ceil(max(row_dest(:)));
minc = floor(min(col_dest(:))); maxc = ceil(max(col_dest(:)));
elseif (strcmp(bbox,'crop'))
minr = rstart; maxr = rend;
minc = cstart; maxc = cend;
else
error('illegal value for bbox');
end;
mrows = maxr-minr+1;
ncols = maxc-minc+1;
% apply inverse homography on meshgrid in destination image
[col_dest_grid,row_dest_grid] = meshgrid( minc:maxc, minr:maxr );
pr = inv(H) * [row_dest_grid(:)'; col_dest_grid(:)'; ones(1,mrows*ncols)];
row_sample_locs = pr(1,:) ./ pr(3,:) + (siz(1)+1)/2;
row_sample_locs = reshape(row_sample_locs,mrows,ncols);
col_sample_locs = pr(2,:) ./ pr(3,:) + (siz(2)+1)/2;
col_sample_locs = reshape(col_sample_locs,mrows,ncols);
% now texture map results
IR = interp2( I, col_sample_locs, row_sample_locs, method );
IR(isnan(IR)) = 0;
IR = arraycrop2dims( IR, size(IR)-6 ); %undo extra padding
if(~strcmp(classname,'double')); IR=feval(classname,IR ); end
% optionally show
if ( show)
I = arraycrop2dims( I, size(IR)-2 );
figure(show); clf; im(I);
figure(show+1); clf; im(IR);
end
|
github
|
3arbouch/PersonDetection-master
|
pca_apply.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/pca_apply.m
| 2,427 |
utf_8
|
0831befb6057f8502bc492227455019a
|
% Companion function to pca.
%
% Use pca to retrieve the principal components U and the mean mu from a
% set fo vectors X1 via [U,mu,vars] = pca(X1). Then given a new
% vector x, use y = pca_apply( x, U, mu, vars, k ) to get the first k
% coefficients of x in the space spanned by the columns of U. See pca for
% general information.
%
% This may prove useful:
% siz = size(X); k = 100;
% Uim = reshape( U(:,1:k), [ siz(1:end-1) k ] );
%
% USAGE
% [ Yk, Xhat, avsq, avsqOrig ] = pca_apply( X, U, mu, vars, k )
%
% INPUTS
% X - array for which to get PCA coefficients
% U - [returned by pca] -- see pca
% mu - [returned by pca] -- see pca
% vars - [returned by pca] -- see pca
% k - number of principal coordinates to approximate X with
%
% OUTPUTS
% Yk - first k coordinates of X in column space of U
% Xhat - approximation of X corresponding to Yk
% avsq - measure of squared error normalized to fall between [0,1]
%
% EXAMPLE
%
% See also PCA, PCA_VISUALIZE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function [Yk,Xhat,avsq,avsqOrig] = pca_apply(X,U,mu,vars,k) %#ok<INUSL>
siz = size(X); nd = ndims(X); [N,r] = size(U);
if(N==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
inds = {':'}; inds = inds(:,ones(1,nd-1));
d= prod(siz(1:end-1));
% some error checking
if(d~=N); error('incorrect size for X or U'); end
if(isa(X,'uint8')); X = double(X); end
if( k>r )
warning(['Only ' int2str(r) '<k comp. available.']); %#ok<WNTAG>
k=r;
end
% subtract mean, then flatten X
Xorig = X;
murep = mu( inds{:}, ones(1,siz(end)));
X = X - murep;
X = reshape(X, d, [] );
% Find Yk, the first k coefficients of X in the new basis
k = min( r, k );
Uk = U(:,1:k);
Yk = Uk' * X;
% calculate Xhat - the approx of X using the first k princ components
if( nargout>1 )
Xhat = Uk * Yk;
Xhat = reshape( Xhat, siz );
Xhat = Xhat + murep;
end
% caclulate average value of (Xhat-Xorig).^2 compared to average value
% of X.^2, where X is Xorig without the mean. This is equivalent to
% what fraction of the variance is captured by Xhat.
if( nargout>2 )
avsq = Xhat - Xorig;
avsq = dot(avsq(:),avsq(:));
avsqOrig = dot(X(:),X(:));
if (nargout==3)
avsq = avsq / avsqOrig;
end
end
|
github
|
3arbouch/PersonDetection-master
|
mode2.m
|
.m
|
PersonDetection-master/Source/toolbox/external/deprecated/mode2.m
| 731 |
utf_8
|
5c9321ef4b610b4f4a2d43902a68838e
|
% Returns the mode of a vector.
%
% Was mode not part of Matlab before?
%
% USAGE
% y = mode2( x )
%
% INPUTS
% x - vector of integers
%
% OUTPUTS
% y - mode
%
% EXAMPLE
% x = randint2( 1, 10, [1 3] )
% mode(x), mode2( x )
%
% See also MODE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function y = mode2( x )
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n MODE is its '...
'recommended replacement.'],upper(mfilename));
y = mode( x );
% [b,i,j] = unique(x);
% [ mval, ind ] = max(hist(j,length(b)));
% y = b(ind);
|
github
|
3arbouch/PersonDetection-master
|
savefig.m
|
.m
|
PersonDetection-master/Source/toolbox/external/other/savefig.m
| 13,459 |
utf_8
|
2b8463f9b01ceb743e440d8fb5755829
|
function savefig(fname, varargin)
% Usage: savefig(filename, fighdl, options)
%
% Saves a pdf, eps, png, jpeg, and/or tiff of the contents of the fighandle's (or current) figure.
% It saves an eps of the figure and the uses Ghostscript to convert to the other formats.
% The result is a cropped, clean picture. There are options for using rgb or cmyk colours,
% or grayscale. You can also choose the resolution.
%
% The advantage of savefig is that there is very little empty space around the figure in the
% resulting files, you can export to more than one format at once, and Ghostscript generates
% trouble-free files.
%
% If you find any errors, please let me know! (peder at axensten dot se)
%
% filename: File name without suffix.
%
% fighdl: (default: gcf) Integer handle to figure.
%
% options: (default: '-r300', '-lossless', '-rgb') You can define your own
% defaults in a global variable savefig_defaults, if you want to, i.e.
% savefig_defaults= {'-r200','-gray'};.
% 'eps': Output in Encapsulated Post Script (no preview yet).
% 'pdf': Output in (Adobe) Portable Document Format.
% 'png': Output in Portable Network Graphics.
% 'jpeg': Output in Joint Photographic Experts Group format.
% 'tiff': Output in Tagged Image File Format (no compression: huge files!).
% '-rgb': Output in rgb colours.
% '-cmyk': Output in cmyk colours (not yet 'png' or 'jpeg' -- '-rgb' is used).
% '-gray': Output in grayscale (not yet 'eps' -- '-rgb' is used).
% '-fonts': Include fonts in eps or pdf. Includes only the subset needed.
% '-lossless': Use lossless compression, works on most formats. same as '-c0', below.
% '-c<float>': Set compression for non-indexed bitmaps in PDFs -
% 0: lossless; 0.1: high quality; 0.5: medium; 1: high compression.
% '-r<integer>': Set resolution.
% '-crop': Removes points and line segments outside the viewing area -- permanently.
% Only use this on figures where many points and/or line segments are outside
% the area zoomed in to. This option will result in smaller vector files (has no
% effect on pixel files).
% '-dbg': Displays gs command line(s).
%
% EXAMPLE:
% savefig('nicefig', 'pdf', 'jpeg', '-cmyk', '-c0.1', '-r250');
% Saves the current figure to nicefig.pdf and nicefig.png, both in cmyk and at 250 dpi,
% with high quality lossy compression.
%
% REQUIREMENT: Ghostscript. Version 8.57 works, probably older versions too, but '-dEPSCrop'
% must be supported. I think version 7.32 or newer is ok.
%
% HISTORY:
% Version 1.0, 2006-04-20.
% Version 1.1, 2006-04-27:
% - No 'epstopdf' stuff anymore! Using '-dEPSCrop' option in gs instead!
% Version 1.2, 2006-05-02:
% - Added a '-dbg' option (see options, above).
% - Now looks for a global variable 'savefig_defaults' (see options, above).
% - More detailed Ghostscript options (user will not really notice).
% - Warns when there is no device for a file-type/color-model combination.
% Version 1.3, 2006-06-06:
% - Added a check to see if there actually is a figure handle.
% - Now works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too).
% - Now compatible with Ghostscript 8.54, released 2006-06-01.
% Version 1.4, 2006-07-20:
% - Added an option '-soft' that enables anti-aliasing on pixel graphics (on by default).
% - Added an option '-hard' that don't do anti-aliasing on pixel graphics.
% Version 1.5, 2006-07-27:
% - Fixed a bug when calling with a figure handle argument.
% Version 1.6, 2006-07-28:
% - Added a crop option, see above.
% Version 1.7, 2007-03-31:
% - Fixed bug: calling print with invalid renderer value '-none'.
% - Removed GhostScript argument '-dUseCIEColor' as it sometimes discoloured things.
% Version 1.8, 2008-01-03:
% - Added MacIntel: 'MACI'.
% - Added 64bit PC (I think, can't test it myself).
% - Added option '-nointerpolate' (use it to prevent blurring of pixelated).
% - Removed '-hard' and '-soft'. Use '-nointerpolate' for '-hard', default for '-soft'.
% - Fixed the gs 8.57 warning on UseCIEColor (it's now set).
% - Added '-gray' for pdf, but gs 8.56 or newer is needed.
% - Added '-gray' and '-cmyk' for eps, but you a fairly recent gs might be needed.
% Version 1.9, 2008-07-27:
% - Added lossless compression, see option '-lossless', above. Works on most formats.
% - Added lossy compression, see options '-c<float>...', above. Works on 'pdf'.
% Thanks to Olly Woodford for idea and implementation!
% - Removed option '-nointerpolate' -- now savefig never interpolates.
% - Fixed a few small bugs and removed some mlint comments.
% Version 2.0, 2008-11-07:
% - Added the possibility to include fonts into eps or pdf.
%
% TO DO: (Need Ghostscript support for these, so don't expect anything soon...)
% - svg output.
% - '-cmyk' for 'jpeg' and 'png'.
% - Preview in 'eps'.
% - Embedded vector fonts, not bitmap, in 'eps'.
%
% Copyright (C) Peder Axensten (peder at axensten dot se), 2006.
% KEYWORDS: eps, pdf, jpg, jpeg, png, tiff, eps2pdf, epstopdf, ghostscript
%
% INSPIRATION: eps2pdf (5782), eps2xxx (6858)
%
% REQUIREMENTS: Works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
op_dbg= false; % Default value.
% Compression
compr= [' -dUseFlateCompression=true -dLZWEncodePages=true -dCompatibilityLevel=1.6' ...
' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false ' ...
' -dColorImageFilter=%s -dGrayImageFilter=%s']; % Compression.
lossless= sprintf (compr, '/FlateEncode', '/FlateEncode');
lossy= sprintf (compr, '/DCTEncode', '/DCTEncode' );
lossy= [lossy ' -c ".setpdfwrite << /ColorImageDict << /QFactor %g ' ...
'/Blend 1 /HSample [%s] /VSample [%s] >> >> setdistillerparams"'];
% Create gs command.
cmdEnd= ' -sDEVICE=%s -sOutputFile="%s"'; % Essential.
epsCmd= '';
epsCmd= [epsCmd ' -dSubsetFonts=true -dNOPLATFONTS']; % Future support?
epsCmd= [epsCmd ' -dUseCIEColor=true -dColorConversionStrategy=/UseDeviceIndependentColor'];
epsCmd= [epsCmd ' -dProcessColorModel=/%s']; % Color conversion.
pdfCmd= [epsCmd ' -dAntiAliasColorImages=false' cmdEnd];
epsCmd= [epsCmd cmdEnd];
% Get file name.
if((nargin < 1) || isempty(fname) || ~ischar(fname)) % Check file name.
error('No file name specified.');
end
[pathstr, namestr] = fileparts(fname);
if(isempty(pathstr)), fname= fullfile(cd, namestr); end
% Get handle.
fighdl= get(0, 'CurrentFigure'); % See gcf. % Get figure handle.
if((nargin >= 2) && (numel(varargin{1}) == 1) && isnumeric(varargin{1}))
fighdl= varargin{1};
varargin= {varargin{2:end}};
end
if(isempty(fighdl)), error('There is no figure to save!?'); end
set(fighdl, 'Units', 'centimeters') % Set paper stuff.
sz= get(fighdl, 'Position');
sz(1:2)= 0;
set(fighdl, 'PaperUnits', 'centimeters', 'PaperSize', sz(3:4), 'PaperPosition', sz);
% Set up the various devices.
% Those commented out are not yet supported by gs (nor by savefig).
% pdf-cmyk works due to the Matlab '-cmyk' export being carried over from eps to pdf.
device.eps.rgb= sprintf(epsCmd, 'DeviceRGB', 'epswrite', [fname '.eps']);
device.jpeg.rgb= sprintf(cmdEnd, 'jpeg', [fname '.jpeg']);
% device.jpeg.cmyk= sprintf(cmdEnd, 'jpegcmyk', [fname '.jpeg']);
device.jpeg.gray= sprintf(cmdEnd, 'jpeggray', [fname '.jpeg']);
device.pdf.rgb= sprintf(pdfCmd, 'DeviceRGB', 'pdfwrite', [fname '.pdf']);
device.pdf.cmyk= sprintf(pdfCmd, 'DeviceCMYK', 'pdfwrite', [fname '.pdf']);
device.pdf.gray= sprintf(pdfCmd, 'DeviceGray', 'pdfwrite', [fname '.pdf']);
device.png.rgb= sprintf(cmdEnd, 'png16m', [fname '.png']);
% device.png.cmyk= sprintf(cmdEnd, 'png???', [fname '.png']);
device.png.gray= sprintf(cmdEnd, 'pnggray', [fname '.png']);
device.tiff.rgb= sprintf(cmdEnd, 'tiff24nc', [fname '.tiff']);
device.tiff.cmyk= sprintf(cmdEnd, 'tiff32nc', [fname '.tiff']);
device.tiff.gray= sprintf(cmdEnd, 'tiffgray', [fname '.tiff']);
% Get options.
global savefig_defaults; % Add global defaults.
if( iscellstr(savefig_defaults)), varargin= {savefig_defaults{:}, varargin{:}};
elseif(ischar(savefig_defaults)), varargin= {savefig_defaults, varargin{:}};
end
varargin= {'-r300', '-lossless', '-rgb', varargin{:}}; % Add defaults.
res= '';
types= {};
fonts= 'false';
crop= false;
for n= 1:length(varargin) % Read options.
if(ischar(varargin{n}))
switch(lower(varargin{n}))
case {'eps','jpeg','pdf','png','tiff'}, types{end+1}= lower(varargin{n});
case '-rgb', color= 'rgb'; deps= {'-depsc2'};
case '-cmyk', color= 'cmyk'; deps= {'-depsc2', '-cmyk'};
case '-gray', color= 'gray'; deps= {'-deps2'};
case '-fonts', fonts= 'true';
case '-lossless', comp= 0;
case '-crop', crop= true;
case '-dbg', op_dbg= true;
otherwise
if(regexp(varargin{n}, '^\-r[0-9]+$')), res= varargin{n};
elseif(regexp(varargin{n}, '^\-c[0-9.]+$')), comp= str2double(varargin{n}(3:end));
else warning('pax:savefig:inputError', 'Unknown option in argument: ''%s''.', varargin{n});
end
end
else
warning('pax:savefig:inputError', 'Wrong type of argument: ''%s''.', class(varargin{n}));
end
end
types= unique(types);
if(isempty(types)), error('No output format given.'); end
if (comp == 0) % Lossless compression
gsCompr= lossless;
elseif (comp <= 0.1) % High quality lossy
gsCompr= sprintf(lossy, comp, '1 1 1 1', '1 1 1 1');
else % Normal lossy
gsCompr= sprintf(lossy, comp, '2 1 1 2', '2 1 1 2');
end
% Generate the gs command.
switch(computer) % Get gs command.
case {'MAC','MACI'}, gs= '/usr/local/bin/gs';
case {'PCWIN'}, gs= 'gswin32c.exe';
case {'PCWIN64'}, gs= 'gswin64c.exe';
otherwise, gs= 'gs';
end
gs= [gs ' -q -dNOPAUSE -dBATCH -dEPSCrop']; % Essential.
gs= [gs ' -dPDFSETTINGS=/prepress -dEmbedAllFonts=' fonts]; % Must be first?
gs= [gs ' -dUseFlateCompression=true']; % Useful stuff.
gs= [gs ' -dAutoRotatePages=/None']; % Probably good.
gs= [gs ' -dHaveTrueTypes']; % Probably good.
gs= [gs ' ' res]; % Add resolution to cmd.
if(crop && ismember(types, {'eps', 'pdf'})) % Crop the figure.
fighdl= do_crop(fighdl);
end
% Output eps from Matlab.
renderer= ['-' lower(get(fighdl, 'Renderer'))]; % Use same as in figure.
if(strcmpi(renderer, '-none')), renderer= '-painters'; end % We need a valid renderer.
deps = [deps '-loose']; % added by PPD seems to help w cropping in matlab 2014b :(
print(fighdl, deps{:}, '-noui', renderer, res, [fname '-temp']); % Output the eps.
% Convert to other formats.
for n= 1:length(types) % Output them.
if(isfield(device.(types{n}), color))
cmd= device.(types{n}).(color); % Colour model exists.
else
cmd= device.(types{n}).rgb; % Use alternative.
if(~strcmp(types{n}, 'eps')) % It works anyways for eps (VERY SHAKY!).
warning('pax:savefig:deviceError', ...
'No device for %s using %s. Using rgb instead.', types{n}, color);
end
end
cmp= lossless;
if (strcmp(types{n}, 'pdf')), cmp= gsCompr; end % Lossy compr only for pdf.
if (strcmp(types{n}, 'eps')), cmp= ''; end % eps can't use lossless.
cmd= sprintf('%s %s %s -f "%s-temp.eps"', gs, cmd, cmp, fname);% Add up.
status= system(cmd); % Run Ghostscript.
if (op_dbg || status), display (cmd), end
end
delete([fname '-temp.eps']); % Clean up.
end
function fig= do_crop(fig)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Remove line segments that are outside the view.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
haxes= findobj(fig, 'Type', 'axes', '-and', 'Tag', '');
for n=1:length(haxes)
xl= get(haxes(n), 'XLim');
yl= get(haxes(n), 'YLim');
lines= findobj(haxes(n), 'Type', 'line');
for m=1:length(lines)
x= get(lines(m), 'XData');
y= get(lines(m), 'YData');
inx= (xl(1) <= x) & (x <= xl(2)); % Within the x borders.
iny= (yl(1) <= y) & (y <= yl(2)); % Within the y borders.
keep= inx & iny; % Within the box.
if(~strcmp(get(lines(m), 'LineStyle'), 'none'))
crossx= ((x(1:end-1) < xl(1)) & (xl(1) < x(2:end))) ... % Crossing border x1.
| ((x(1:end-1) < xl(2)) & (xl(2) < x(2:end))) ... % Crossing border x2.
| ((x(1:end-1) > xl(1)) & (xl(1) > x(2:end))) ... % Crossing border x1.
| ((x(1:end-1) > xl(2)) & (xl(2) > x(2:end))); % Crossing border x2.
crossy= ((y(1:end-1) < yl(1)) & (yl(1) < y(2:end))) ... % Crossing border y1.
| ((y(1:end-1) < yl(2)) & (yl(2) < y(2:end))) ... % Crossing border y2.
| ((y(1:end-1) > yl(1)) & (yl(1) > y(2:end))) ... % Crossing border y1.
| ((y(1:end-1) > yl(2)) & (yl(2) > y(2:end))); % Crossing border y2.
crossp= [( (crossx & iny(1:end-1) & iny(2:end)) ... % Crossing a x border within y limits.
| (crossy & inx(1:end-1) & inx(2:end)) ... % Crossing a y border within x limits.
| crossx & crossy ... % Crossing a x and a y border (corner).
), false ...
];
crossp(2:end)= crossp(2:end) | crossp(1:end-1); % Add line segment's secont end point.
keep= keep | crossp;
end
set(lines(m), 'XData', x(keep))
set(lines(m), 'YData', y(keep))
end
end
end
|
github
|
3arbouch/PersonDetection-master
|
dirSynch.m
|
.m
|
PersonDetection-master/Source/toolbox/matlab/dirSynch.m
| 4,570 |
utf_8
|
d288299d31d15f1804183206d0aa0227
|
function dirSynch( root1, root2, showOnly, flag, ignDate )
% Synchronize two directory trees (or show differences between them).
%
% If a file or directory 'name' is found in both tree1 and tree2:
% 1) if 'name' is a file in both the pair is considered the same if they
% have identical size and identical datestamp (or if ignDate=1).
% 2) if 'name' is a directory in both the dirs are searched recursively.
% 3) if 'name' is a dir in root1 and a file in root2 (or vice-versa)
% synchronization cannot proceed (an error is thrown).
% If 'name' is found only in root1 or root2 it's a difference between them.
%
% The parameter flag controls how synchronization occurs:
% flag==0: neither tree1 nor tree2 has preference (newer file is kept)
% flag==1: tree2 is altered to reflect tree1 (tree1 is unchanged)
% flag==2: tree1 is altered to reflect tree2 (tree2 is unchanged)
% Run with showOnly=1 and different values of flag to see its effect.
%
% By default showOnly==1. If showOnly, displays a list of actions that need
% to be performed in order to synchronize the two directory trees, but does
% not actually perform the actions. It is highly recommended to run
% dirSynch first with showOnly=1 before running it with showOnly=0.
%
% USAGE
% dirSynch( root1, root2, [showOnly], [flag], [ignDate] )
%
% INPUTS
% root1 - root directory of tree1
% root2 - root directory of tree2
% showOnly - [1] show but do NOT perform actions
% flag - [0] 0: synchronize; 1: set root2=root1; 2: set root1==root2
% ignDate - [0] if true considers two files same even if have diff dates
%
% OUTPUTS
% dirSynch( 'c:\toolbox', 'c:\toolbox-old', 1 )
%
% EXAMPLE
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 2.10
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if(nargin<3 || isempty(showOnly)), showOnly=1; end;
if(nargin<4 || isempty(flag)), flag=0; end;
if(nargin<5 || isempty(ignDate)), ignDate=0; end;
% get differences between root1/root2 and loop over them
D = dirDiff( root1, root2, ignDate );
roots={root1,root2}; ticId = ticStatus;
for i=1:length(D)
% get action
if( flag==1 )
if( D(i).in1 ), act=1; src1=1; else act=0; src1=2; end
elseif( flag==2 )
if( D(i).in2 ), act=1; src1=2; else act=0; src1=1; end
else
act=1;
if(D(i).in1 && D(i).in2)
if( D(i).new1 ), src1=1; else src1=2; end
else
if( D(i).in1 ), src1=1; else src1=2; end
end
end
src2=mod(src1,2)+1;
% perform action
if( act==1 )
if( showOnly )
disp(['COPY ' int2str(src1) '->' int2str(src2) ': ' D(i).name]);
else
copyfile( [roots{src1} D(i).name], [roots{src2} D(i).name], 'f' );
end;
else
if( showOnly )
disp(['DEL in ' int2str(src1) ': ' D(i).name]);
else
fName = [roots{src1} D(i).name];
if(D(i).isdir), rmdir(fName,'s'); else delete(fName); end
end
end
if(~showOnly), tocStatus( ticId, i/length(D) ); end;
end
end
function D = dirDiff( root1, root2, ignDate )
% get differences from root1 to root2
D1 = dirDiff1( root1, root2, ignDate, '/' );
% get differences from root2 to root1
D2 = dirDiff1( root2, root1, ignDate, '/' );
% remove duplicates (arbitrarily from D2)
D2=D2(~([D2.in1] & [D2.in2]));
% swap 1 and 2 in D2
for i=1:length(D2),
D2(i).in1=0; D2(i).in2=1; D2(i).new1=~D2(i).new1;
end
% merge
D = [D1 D2];
end
function D = dirDiff1( root1, root2, ignDate, subdir )
if(root1(end)~='/'), root1(end+1)='/'; end
if(root2(end)~='/'), root2(end+1)='/'; end
if(subdir(end)~='/'), subdir(end+1)='/'; end
fs1=dir([root1 subdir]); fs2=dir([root2 subdir]);
D=struct('name',0,'isdir',0,'in1',0,'in2',0,'new1',0);
D=repmat(D,[1 length(fs1)]); n=0; names2={fs2.name}; Dsub=[];
for i1=1:length( fs1 )
name=fs1(i1).name; isdir=fs1(i1).isdir;
if( any(strcmp(name,{'.','..'})) ), continue; end;
i2 = find(strcmp(name,names2));
if(~isempty(i2) && isdir)
% cannot handle this condition
if(~fs2(i2).isdir), disp([root1 subdir name]); assert(false); end;
% recurse and record possible differences
Dsub=[Dsub dirDiff1(root1,root2,ignDate,[subdir name])]; %#ok<AGROW>
elseif( ~isempty(i2) && fs1(i1).bytes==fs2(i2).bytes && ...
(ignDate || fs1(i1).datenum==fs2(i2).datenum))
% nothing to do - files are same
continue;
else
% record differences
n=n+1;
D(n).name=[subdir name]; D(n).isdir=isdir;
D(n).in1=1; D(n).in2=~isempty(i2);
D(n).new1 = ~D(n).in2 || (fs1(i1).datenum>fs2(i2).datenum);
end
end
D = [D(1:n) Dsub];
end
|
github
|
3arbouch/PersonDetection-master
|
plotRoc.m
|
.m
|
PersonDetection-master/Source/toolbox/matlab/plotRoc.m
| 5,212 |
utf_8
|
008f9c63073c6400c4960e9e213c47e5
|
function [h,miss,stds] = plotRoc( D, varargin )
% Function for display of rocs (receiver operator characteristic curves).
%
% Display roc curves. Consistent usage ensures uniform look for rocs. The
% input D should have n rows, each of which is of the form:
% D = [falsePosRate truePosRate]
% D is generated, for example, by scanning a detection threshold over n
% values from 0 (so first entry is [1 1]) to 1 (so last entry is [0 0]).
% Alternatively D can be a cell vector of rocs, in which case an average
% ROC will be shown with error bars. Plots missRate (which is just 1 minus
% the truePosRate) on the y-axis versus the falsePosRate on the x-axis.
%
% USAGE
% [h,miss,stds] = plotRoc( D, prm )
%
% INPUTS
% D - [nx2] n data points along roc [falsePosRate truePosRate]
% typically ranges from [1 1] to [0 0] (or may be reversed)
% prm - [] param struct
% .color - ['g'] color for curve
% .lineSt - ['-'] linestyle (see LineSpec)
% .lineWd - [4] curve width
% .logx - [0] use logarithmic scale for x-axis
% .logy - [0] use logarithmic scale for y-axis
% .marker - [''] marker type (see LineSpec)
% .mrkrSiz - [12] marker size
% .nMarker - [5] number of markers (regularly spaced) to display
% .lims - [0 1 0 1] axes limits
% .smooth - [0] if T compute lower envelop of roc to smooth staircase
% .fpTarget - [] return miss rates at given fp values (and draw lines)
% .xLbl - ['false positive rate'] label for x-axis
% .yLbl - ['miss rate'] label for y-axis
%
% OUTPUTS
% h - plot handle for use in legend only
% miss - average miss rates at fpTarget reference values
% stds - standard deviation of miss rates at fpTarget reference values
%
% EXAMPLE
% k=2; x=0:.0001:1; data1 = [1-x; (1-x.^k).^(1/k)]';
% k=3; x=0:.0001:1; data2 = [1-x; (1-x.^k).^(1/k)]';
% hs(1)=plotRoc(data1,struct('color','g','marker','s'));
% hs(2)=plotRoc(data2,struct('color','b','lineSt','--'));
% legend( hs, {'roc1','roc2'} ); xlabel('fp'); ylabel('fn');
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.02
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get params
[color,lineSt,lineWd,logx,logy,marker,mrkrSiz,nMarker,lims,smooth, ...
fpTarget,xLbl,yLbl] = getPrmDflt( varargin, {'color' 'g' 'lineSt' '-' ...
'lineWd' 4 'logx' 0 'logy' 0 'marker' '' 'mrkrSiz' 12 'nMarker' 5 ...
'lims' [] 'smooth' 0 'fpTarget' [] 'xLbl' 'false positive rate' ...
'yLbl' 'miss rate' } );
if( isempty(lims) ); lims=[logx*1e-5 1 logy*1e-5 1]; end
% ensure descending fp rate, change to miss rate, optionally 'nicefy' roc
if(~iscell(D)), D={D}; end; nD=length(D);
for j=1:nD, assert(size(D{j},2)==2); end
for j=1:nD, if(D{j}(1,2)<D{j}(end,2)), D{j}=flipud(D{j}); end; end
for j=1:nD, D{j}(:,2)=1-D{j}(:,2); assert(all(D{j}(:,2)>=0)); end
if(smooth), for j=1:nD, D{j}=smoothRoc(D{j}); end; end
% plot: (1) h for legend only, (2) markers, (3) error bars, (4) roc curves
hold on; axis(lims); xlabel(xLbl); ylabel(yLbl);
prmMrkr = {'MarkerSize',mrkrSiz,'MarkerFaceColor',color};
prmClr={'Color',color}; prmPlot = [prmClr,{'LineWidth',lineWd}];
h = plot( 2, 0, [lineSt marker], prmMrkr{:}, prmPlot{:} ); %(1)
DQ = quantizeRocs( D, nMarker, logx, lims ); DQm=mean(DQ,3);
if(~isempty(marker))
plot(DQm(:,1),DQm(:,2),marker,prmClr{:},prmMrkr{:} ); end %(2)
if(nD>1), DQs=std(DQ,0,3);
errorbar(DQm(:,1),DQm(:,2),DQs(:,2),'.',prmClr{:}); end %(3)
if(nD==1), DQ=D{1}; else DQ=quantizeRocs(D,100,logx,lims); end
DQm = mean(DQ,3); plot( DQm(:,1), DQm(:,2), lineSt, prmPlot{:} ); %(4)
% plot line at given fp rate
m=length(fpTarget); miss=zeros(1,m); stds=miss;
if( m>0 )
assert( min(DQm(:,1))<=min(fpTarget) ); DQs=std(DQ,0,3);
for i=1:m, j=find(DQm(:,1)<=fpTarget(i)); j=j(1);
miss(i)=DQm(j,2); stds(i)=DQs(j,2); end
fp=min(fpTarget); plot([fp fp],lims(3:4),'Color',.7*[1 1 1]);
fp=max(fpTarget); plot([fp fp],lims(3:4),'Color',.7*[1 1 1]);
end
% set log axes
if( logx==1 )
ticks=10.^(-8:8);
set(gca,'XScale','log','XTick',ticks);
end
if( logy==1 )
ticks=[.001 .002 .005 .01 .02 .05 .1 .2 .5 1];
set(gca,'YScale','log','YTick',ticks);
end
if( logx==1 || logy==1 ), grid on;
set(gca,'XMinorGrid','off','XMinorTic','off');
set(gca,'YMinorGrid','off','YMinorTic','off');
end
end
function DQ = quantizeRocs( Ds, nPnts, logx, lims )
% estimate miss rate at each target fp rate
nD=length(Ds); DQ=zeros(nPnts,2,nD);
if(logx==1), fps=logspace(log10(lims(1)),log10(lims(2)),nPnts);
else fps=linspace(lims(1),lims(2),nPnts); end; fps=flipud(fps');
for j=1:nD, D=[Ds{j}; 0 1]; k=1; fp=D(k,1);
for i=1:nPnts
while( k<size(D,1) && fp>=fps(i) ), k=k+1; fp=D(k,1); end
k0=max(k-1,1); fp0=D(k0,1); assert(fp0>=fp);
if(fp0==fp), r=.5; else r=(fps(i)-fp)/(fp0-fp); end
DQ(i,1,j)=fps(i); DQ(i,2,j)=r*D(k0,2)+(1-r)*D(k,2);
end
end
end
function D1 = smoothRoc( D )
D1 = zeros(size(D));
n = size(D,1); cnt=0;
for i=1:n
isAnkle = (i==1) || (i==n);
if( ~isAnkle )
dP=D1(cnt,:); dC=D(i,:); dN=D(i+1,:);
isAnkle = (dC(1)~=dP(1)) && (dC(2)~=dN(2));
end
if(isAnkle); cnt=cnt+1; D1(cnt,:)=D(i,:); end
end
D1=D1(1:cnt,:);
end
|
github
|
3arbouch/PersonDetection-master
|
simpleCache.m
|
.m
|
PersonDetection-master/Source/toolbox/matlab/simpleCache.m
| 4,098 |
utf_8
|
92df86b0b7e919c9a26388e598e4d370
|
function varargout = simpleCache( op, cache, varargin )
% A simple cache that can be used to store results of computations.
%
% Can save and retrieve arbitrary values using a vector (includnig char
% vectors) as a key. Especially useful if a function must perform heavy
% computation but is often called with the same inputs (for which it will
% give the same outputs). Note that the current implementation does a
% linear search for the key (a more refined implementation would use a hash
% table), so it is not meant for large scale usage.
%
% To use inside a function, make the cache persistent:
% persistent cache; if( isempty(cache) ) cache=simpleCache('init'); end;
% The following line, when placed inside a function, means the cache will
% stay in memory until the matlab environment changes. For an example
% usage see maskGaussians.
%
% USAGE - 'init': initialize a cache object
% cache = simpleCache('init');
%
% USAGE - 'put': put something in cache. key must be a numeric vector
% cache = simpleCache( 'put', cache, key, val );
%
% USAGE - 'get': retrieve from cache. found==1 if obj was found
% [found,val] = simpleCache( 'get', cache, key );
%
% USAGE - 'remove': free key
% [cache,found] = simpleCache( 'remove', cache, key );
%
% INPUTS
% op - 'init', 'put', 'get', 'remove'
% cache - the cache object being operated on
% varargin - see USAGE above
%
% OUTPUTS
% varargout - see USAGE above
%
% EXAMPLE
% cache = simpleCache('init');
% hellokey=rand(1,3); worldkey=rand(1,11);
% cache = simpleCache( 'put', cache, hellokey, 'hello' );
% cache = simpleCache( 'put', cache, worldkey, 'world' );
% [f,v]=simpleCache( 'get', cache, hellokey ); disp(v);
% [f,v]=simpleCache( 'get', cache, worldkey ); disp(v);
%
% See also PERSISTENT, MASKGAUSSIANS
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
switch op
case 'init' % init a cache
cacheSiz = 8;
cache.freeinds = 1:cacheSiz;
cache.keyns = -ones(1,cacheSiz);
cache.keys = cell(1,cacheSiz);
cache.vals = cell(1,cacheSiz);
varargout = {cache};
case 'put' % a put operation
key=varargin{1}; val=varargin{2};
cache = cacheput( cache, key, val );
varargout = {cache};
case 'get' % a get operation
key=varargin{1};
[ind,val] = cacheget( cache, key );
found = ind>0;
varargout = {found,val};
case 'remove' % a remove operation
key=varargin{1};
[cache,found] = cacheremove( cache, key );
varargout = {cache,found};
otherwise
error('Unknown cache operation: %s',op);
end
end
function cache = cachegrow( cache )
% double cache size
cacheSiz = length( cache.keyns );
if( cacheSiz>64 ) % warn if getting big
warning(['doubling cache size to: ' int2str2(cacheSiz*2)]);%#ok<WNTAG>
end
cache.freeinds = [cache.freeinds (cacheSiz+1):(2*cacheSiz)];
cache.keyns = [cache.keyns -ones(1,cacheSiz)];
cache.keys = [cache.keys cell(1,cacheSiz)];
cache.vals = [cache.vals cell(1,cacheSiz)];
end
function cache = cacheput( cache, key, val )
% put something into the cache
% get location to place
ind = cacheget( cache, key ); % see if already in cache
if( ind==-1 )
if( isempty( cache.freeinds ) )
cache = cachegrow( cache ); %grow cache
end
ind = cache.freeinds(1); % get new cache loc
cache.freeinds = cache.freeinds(2:end);
end
% now simply place in ind
cache.keyns(ind) = length(key);
cache.keys{ind} = key;
cache.vals{ind} = val;
end
function [ind,val] = cacheget( cache, key )
% get cache element, or fail
cacheSiz = length( cache.keyns );
keyn = length( key );
for i=1:cacheSiz
if(keyn==cache.keyns(i) && all(key==cache.keys{i}))
val = cache.vals{i}; ind = i; return; end
end
ind=-1; val=-1;
end
function [cache,found] = cacheremove( cache, key )
% get cache element, or fail
ind = cacheget( cache, key );
found = ind>0;
if( found )
cache.freeinds = [ind cache.freeinds];
cache.keyns(ind) = -1;
cache.keys{ind} = [];
cache.vals{ind} = [];
end
end
|
github
|
3arbouch/PersonDetection-master
|
tpsInterpolate.m
|
.m
|
PersonDetection-master/Source/toolbox/matlab/tpsInterpolate.m
| 1,646 |
utf_8
|
d3bd3a26d048f32cfdc17884ccae6d8c
|
function [xsR,ysR] = tpsInterpolate( warp, xs, ys, show )
% Apply warp (obtained by tpsGetWarp) to a set of new points.
%
% USAGE
% [xsR,ysR] = tpsInterpolate( warp, xs, ys, [show] )
%
% INPUTS
% warp - [see tpsGetWarp] bookstein warping parameters
% xs, ys - points to apply warp to
% show - [1] will display results in figure(show)
%
% OUTPUTS
% xsR, ysR - result of warp applied to xs, ys
%
% EXAMPLE
%
% See also TPSGETWARP
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<4 || isempty(show)); show = 1; end
wx = warp.wx; affinex = warp.affinex;
wy = warp.wy; affiney = warp.affiney;
xsS = warp.xsS; ysS = warp.ysS;
xsD = warp.xsD; ysD = warp.ysD;
% interpolate points (xs,ys)
xsR = f( wx, affinex, xsS, ysS, xs(:)', ys(:)' );
ysR = f( wy, affiney, xsS, ysS, xs(:)', ys(:)' );
% optionally show points (xsR, ysR)
if( show )
figure(show);
subplot(2,1,1); plot( xs, ys, '.', 'color', [0 0 1] );
hold('on'); plot( xsS, ysS, '+' ); hold('off');
subplot(2,1,2); plot( xsR, ysR, '.' );
hold('on'); plot( xsD, ysD, '+' ); hold('off');
end
function zs = f( w, aff, xsS, ysS, xs, ys )
% find f(x,y) for xs and ys given W and original points
n = size(w,1); ns = size(xs,2);
delXs = xs'*ones(1,n) - ones(ns,1)*xsS;
delYs = ys'*ones(1,n) - ones(ns,1)*ysS;
distSq = (delXs .* delXs + delYs .* delYs);
distSq = distSq + eye(size(distSq)) + eps;
U = distSq .* log( distSq ); U( isnan(U) )=0;
zs = aff(1)*ones(ns,1)+aff(2)*xs'+aff(3)*ys';
zs = zs + sum((U.*(ones(ns,1)*w')),2);
|
github
|
3arbouch/PersonDetection-master
|
checkNumArgs.m
|
.m
|
PersonDetection-master/Source/toolbox/matlab/checkNumArgs.m
| 3,796 |
utf_8
|
726c125c7dc994c4989c0e53ad4be747
|
function [ x, er ] = checkNumArgs( x, siz, intFlag, signFlag )
% Helper utility for checking numeric vector arguments.
%
% Runs a number of tests on the numeric array x. Tests to see if x has all
% integer values, all positive values, and so on, depending on the values
% for intFlag and signFlag. Also tests to see if the size of x matches siz
% (unless siz==[]). If x is a scalar, x is converted to a array simply by
% creating a matrix of size siz with x in each entry. This is why the
% function returns x. siz=M is equivalent to siz=[M M]. If x does not
% satisfy some criteria, an error message is returned in er. If x satisfied
% all the criteria er=''. Note that error('') has no effect, so can use:
% [ x, er ] = checkNumArgs( x, ... ); error(er);
% which will throw an error only if something was wrong with x.
%
% USAGE
% [ x, er ] = checkNumArgs( x, siz, intFlag, signFlag )
%
% INPUTS
% x - numeric array
% siz - []: does not test size of x
% - [if not []]: intended size for x
% intFlag - -1: no need for integer x
% 0: error if non integer x
% 1: error if non odd integers
% 2: error if non even integers
% signFlag - -2: entires of x must be strictly negative
% -1: entires of x must be negative
% 0: no contstraints on sign of entries in x
% 1: entires of x must be positive
% 2: entires of x must be strictly positive
%
% OUTPUTS
% x - if x was a scalar it may have been replicated into a matrix
% er - contains error msg if anything was wrong with x
%
% EXAMPLE
% a=1; [a, er]=checkNumArgs( a, [1 3], 2, 0 ); a, error(er)
%
% See also NARGCHK
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
xname = inputname(1); er='';
if( isempty(siz) ); siz = size(x); end;
if( length(siz)==1 ); siz=[siz siz]; end;
% first check that x is numeric
if( ~isnumeric(x) ); er = [xname ' not numeric']; return; end;
% if x is a scalar, simply replicate it.
xorig = x; if( length(x)==1); x = x(ones(siz)); end;
% regardless, must have same number of x as n
if( length(siz)~=ndims(x) || ~all(size(x)==siz) )
er = ['has size = [' num2str(size(x)) '], '];
er = [er 'which is not the required size of [' num2str(siz) ']'];
er = createErrMsg( xname, xorig, er ); return;
end
% check that x are the right type of integers (unless intFlag==-1)
switch intFlag
case 0
if( ~all(mod(x,1)==0))
er = 'must have integer entries';
er = createErrMsg( xname, xorig, er); return;
end;
case 1
if( ~all(mod(x,2)==1))
er = 'must have odd integer entries';
er = createErrMsg( xname, xorig, er); return;
end;
case 2
if( ~all(mod(x,2)==0))
er = 'must have even integer entries';
er = createErrMsg( xname, xorig, er ); return;
end;
end;
% check sign of entries in x (unless signFlag==0)
switch signFlag
case -2
if( ~all(x<0))
er = 'must have strictly negative entries';
er = createErrMsg( xname, xorig, er ); return;
end;
case -1
if( ~all(x<=0))
er = 'must have negative entries';
er = createErrMsg( xname, xorig, er ); return;
end;
case 1
if( ~all(x>=0))
er = 'must have positive entries';
er = createErrMsg( xname, xorig, er ); return;
end;
case 2
if( ~all(x>0))
er = 'must have strictly positive entries';
er = createErrMsg( xname, xorig, er ); return;
end
end
function er = createErrMsg( xname, x, er )
if(numel(x)<10)
er = ['Numeric input argument ' xname '=[' num2str(x) '] ' er '.'];
else
er = ['Numeric input argument ' xname ' ' er '.'];
end
|
github
|
3arbouch/PersonDetection-master
|
fevalDistr.m
|
.m
|
PersonDetection-master/Source/toolbox/matlab/fevalDistr.m
| 11,227 |
utf_8
|
7e4d5077ef3d7a891b2847cb858a2c6c
|
function [out,res] = fevalDistr( funNm, jobs, varargin )
% Wrapper for embarrassingly parallel function evaluation.
%
% Runs "r=feval(funNm,jobs{i}{:})" for each job in a parallel manner. jobs
% should be a cell array of length nJob and each job should be a cell array
% of parameters to pass to funNm. funNm must be a function in the path and
% must return a single value (which may be a dummy value if funNm writes
% results to disk). Different forms of parallelization are supported
% depending on the hardware and Matlab toolboxes available. The type of
% parallelization is determined by the parameter 'type' described below.
%
% type='LOCAL': jobs are executed using a simple "for" loop. This implies
% no parallelization and is the default fallback option.
%
% type='PARFOR': jobs are executed using a "parfor" loop. This option is
% only available if the Matlab *Parallel Computing Toolbox* is installed.
% Make sure to setup Matlab workers first using "matlabpool open".
%
% type='DISTR': jobs are executed on the Caltech cluster. Distributed
% queuing system must be installed separately. Currently this option is
% only supported on the Caltech cluster but could easily be installed on
% any Linux cluster as it requires only SSH and a shared filesystem.
% Parameter pLaunch is used for controller('launchQueue',pLaunch{:}) and
% determines cluster machines used (e.g. pLaunch={48,401:408}).
%
% type='COMPILED': jobs are executed locally in parallel by first compiling
% an executable and then running it in background. This option requires the
% *Matlab Compiler* to be installed (but does NOT require the Parallel
% Computing Toolbox). Compiling can take 1-10 minutes, so use this option
% only for large jobs. (On Linux alter startup.m by calling addpath() only
% if ~isdeployed, otherwise will get error about "CTF" after compiling).
% Note that relative paths will not work after compiling so all paths used
% by funNm must be absolute paths.
%
% type='WINHPC': jobs are executed on a Windows HPC Server 2008 cluster.
% Similar to type='COMPILED', except after compiling, the executable is
% queued to the HPC cluster where all computation occurs. This option
% likewise requires the *Matlab Compiler*. Paths to data, etc., must be
% absolute paths and available from HPC cluster. Parameter pLaunch must
% have two fields 'scheduler' and 'shareDir' that define the HPC Server.
% Extra parameters in pLaunch add finer control, see fedWinhpc for details.
% For example, at MSR one possible cluster is defined by scheduler =
% 'MSR-L25-DEV21' and shareDir = '\\msr-arrays\scratch\msr-pool\L25-dev21'.
% Note call to 'job submit' from Matlab will hang unless pwd is saved
% (simply call 'job submit' from cmd prompt and enter pwd).
%
% USAGE
% [out,res] = fevalDistr( funNm, jobs, [varargin] )
%
% INPUTS
% funNm - name of function that will process jobs
% jobs - [1xnJob] cell array of parameters for each job
% varargin - additional params (struct or name/value pairs)
% .type - ['local'], 'parfor', 'distr', 'compiled', 'winhpc'
% .pLaunch - [] extra params for type='distr' or type='winhpc'
% .group - [1] send jobs in batches (only relevant if type='distr')
%
% OUTPUTS
% out - 1 if jobs completed successfully
% res - [1xnJob] cell array containing results of each job
%
% EXAMPLE
% % Note: in this case parallel versions are slower since conv2 is so fast
% n=16; jobs=cell(1,n); for i=1:n, jobs{i}={rand(500),ones(25)}; end
% tic, [out,J1] = fevalDistr('conv2',jobs,'type','local'); toc,
% tic, [out,J2] = fevalDistr('conv2',jobs,'type','parfor'); toc,
% tic, [out,J3] = fevalDistr('conv2',jobs,'type','compiled'); toc
% [isequal(J1,J2), isequal(J1,J3)], figure(1); montage2(cell2array(J1))
%
% See also matlabpool mcc
%
% Piotr's Computer Vision Matlab Toolbox Version 3.26
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
dfs={'type','local','pLaunch',[],'group',1};
[type,pLaunch,group]=getPrmDflt(varargin,dfs,1); store=(nargout==2);
if(isempty(jobs)), res=cell(1,0); out=1; return; end
switch lower(type)
case 'local', [out,res]=fedLocal(funNm,jobs,store);
case 'parfor', [out,res]=fedParfor(funNm,jobs,store);
case 'distr', [out,res]=fedDistr(funNm,jobs,pLaunch,group,store);
case 'compiled', [out,res]=fedCompiled(funNm,jobs,store);
case 'winhpc', [out,res]=fedWinhpc(funNm,jobs,pLaunch,store);
otherwise, error('unkown type: ''%s''',type);
end
end
function [out,res] = fedLocal( funNm, jobs, store )
% Run jobs locally using for loop.
nJob=length(jobs); res=cell(1,nJob); out=1;
tid=ticStatus('collecting jobs');
for i=1:nJob, r=feval(funNm,jobs{i}{:});
if(store), res{i}=r; end; tocStatus(tid,i/nJob); end
end
function [out,res] = fedParfor( funNm, jobs, store )
% Run jobs locally using parfor loop.
nJob=length(jobs); res=cell(1,nJob); out=1;
parfor i=1:nJob, r=feval(funNm,jobs{i}{:});
if(store), res{i}=r; end; end
end
function [out,res] = fedDistr( funNm, jobs, pLaunch, group, store )
% Run jobs using Linux queuing system.
if(~exist('controller.m','file'))
msg='distributed queuing not installed, switching to type=''local''.';
warning(msg); [out,res]=fedLocal(funNm,jobs,store); return; %#ok<WNTAG>
end
nJob=length(jobs); res=cell(1,nJob); controller('launchQueue',pLaunch{:});
if( group>1 )
nJobGrp=ceil(nJob/group); jobsGrp=cell(1,nJobGrp); k=0;
for i=1:nJobGrp, k1=min(nJob,k+group);
jobsGrp{i}={funNm,jobs(k+1:k1),'type','local'}; k=k1; end
nJob=nJobGrp; jobs=jobsGrp; funNm='fevalDistr';
end
jids=controller('jobsAdd',nJob,funNm,jobs); k=0;
fprintf('Sent %i jobs...\n',nJob); tid=ticStatus('collecting jobs');
while( 1 )
jids1=controller('jobProbe',jids);
if(isempty(jids1)), pause(.1); continue; end
jid=jids1(1); [r,err]=controller('jobRecv',jid);
if(~isempty(err)), disp('ABORTING'); out=0; break; end
k=k+1; if(store), res{jid==jids}=r; end
tocStatus(tid,k/nJob); if(k==nJob), out=1; break; end
end; controller('closeQueue');
end
function [out,res] = fedCompiled( funNm, jobs, store )
% Run jobs locally in background in parallel using compiled code.
nJob=length(jobs); res=cell(1,nJob); tDir=jobSetup('.',funNm,'',{});
cmd=[tDir 'fevalDistrDisk ' funNm ' ' tDir ' ']; i=0; k=0;
Q=feature('numCores'); q=0; tid=ticStatus('collecting jobs');
while( 1 )
% launch jobs until queue is full (q==Q) or all jobs launched (i==nJob)
while(q<Q && i<nJob), q=q+1; i=i+1; jobSave(tDir,jobs{i},i);
if(ispc), system2(['start /B /min ' cmd int2str2(i,10)],0);
else system2([cmd int2str2(i,10) ' &'],0); end
end
% collect completed jobs (k1 of them), release queue slots
done=jobFileIds(tDir,'done'); k1=length(done); k=k+k1; q=q-k1;
for i1=done, res{i1}=jobLoad(tDir,i1,store); end
pause(1); tocStatus(tid,k/nJob); if(k==nJob), out=1; break; end
end
for i=1:10, try rmdir(tDir,'s'); break; catch,pause(1),end; end %#ok<CTCH>
end
function [out,res] = fedWinhpc( funNm, jobs, pLaunch, store )
% Run jobs using Windows HPC Server.
nJob=length(jobs); res=cell(1,nJob);
dfs={'shareDir','REQ','scheduler','REQ','executable','fevalDistrDisk',...
'mccOptions',{},'coresPerTask',1,'minCores',1024,'priority',2000};
p = getPrmDflt(pLaunch,dfs,1);
tDir = jobSetup(p.shareDir,funNm,p.executable,p.mccOptions);
for i=1:nJob, jobSave(tDir,jobs{i},i); end
hpcSubmit(funNm,1:nJob,tDir,p); k=0;
ticId=ticStatus('collecting jobs');
while( 1 )
done=jobFileIds(tDir,'done'); k=k+length(done);
for i1=done, res{i1}=jobLoad(tDir,i1,store); end
pause(5); tocStatus(ticId,k/nJob); if(k==nJob), out=1; break; end
end
for i=1:10, try rmdir(tDir,'s'); break; catch,pause(5),end; end %#ok<CTCH>
end
function tids = hpcSubmit( funNm, ids, tDir, pLaunch )
% Helper: send jobs w given ids to HPC cluster.
n=length(ids); tids=cell(1,n); if(n==0), return; end;
scheduler=[' /scheduler:' pLaunch.scheduler ' '];
m=system2(['cluscfg view' scheduler],0);
minCores=(hpcParse(m,'total number of nodes',1) - ...
hpcParse(m,'Unreachable nodes',1) - 1)*8;
minCores=min([minCores pLaunch.minCores n*pLaunch.coresPerTask]);
m=system2(['job new /numcores:' int2str(minCores) '-*' scheduler ...
'/priority:' int2str(pLaunch.priority)],1);
jid=hpcParse(m,'created job, id',0);
s=min(ids); e=max(ids); p=n>1 && isequal(ids,s:e);
if(p), jid1=[jid '.1']; else jid1=jid; end
for i=1:n, tids{i}=[jid1 '.' int2str(i)]; end
cmd0=''; if(p), cmd0=['/parametric:' int2str(s) '-' int2str(e)]; end
cmd=@(id) ['job add ' jid scheduler '/workdir:' tDir ' /numcores:' ...
int2str(pLaunch.coresPerTask) ' ' cmd0 ' /stdout:stdout' id ...
'.txt ' pLaunch.executable ' ' funNm ' ' tDir ' ' id];
if(p), ids1='*'; n=1; else ids1=int2str2(ids); end
if(n==1), ids1={ids1}; end; for i=1:n, system2(cmd(ids1{i}),1); end
system2(['job submit /id:' jid scheduler],1); disp(repmat(' ',1,80));
end
function v = hpcParse( msg, key, tonum )
% Helper: extract val corresponding to key in hpc msg.
t=regexp(msg,': |\n','split'); t=strtrim(t(1:floor(length(t)/2)*2));
keys=t(1:2:end); vals=t(2:2:end); j=find(strcmpi(key,keys));
if(isempty(j)), error('key ''%s'' not found in:\n %s',key,msg); end
v=vals{j}; if(tonum==0), return; elseif(isempty(v)), v=0; return; end
if(tonum==1), v=str2double(v); return; end
v=regexp(v,' ','split'); v=str2double(regexp(v{1},':','split'));
if(numel(v)==4), v(5)=0; end; v=((v(1)*24+v(2))*60+v(3))*60+v(4)+v(5)/1000;
end
function tDir = jobSetup( rtDir, funNm, executable, mccOptions )
% Helper: prepare by setting up temporary dir and compiling funNm
t=clock; t=mod(t(end),1); t=round((t+rand)/2*1e15);
tDir=[rtDir filesep sprintf('fevalDistr-%015i',t) filesep]; mkdir(tDir);
if(~isempty(executable) && exist(executable,'file'))
fprintf('Reusing compiled executable...\n'); copyfile(executable,tDir);
else
t=clock; fprintf('Compiling (this may take a while)...\n');
[~,f,e]=fileparts(executable); if(isempty(f)), f='fevalDistrDisk'; end
mcc('-m','fevalDistrDisk','-d',tDir,'-o',f,'-a',funNm,mccOptions{:});
t=etime(clock,t); fprintf('Compile complete (%.1f seconds).\n',t);
if(~isempty(executable)), copyfile([tDir filesep f e],executable); end
end
end
function ids = jobFileIds( tDir, type )
% Helper: get list of job files ids on disk of given type
fs=dir([tDir '*-' type '*']); fs={fs.name}; n=length(fs);
ids=zeros(1,n); for i=1:n, ids(i)=str2double(fs{i}(1:10)); end
end
function jobSave( tDir, job, ind ) %#ok<INUSL>
% Helper: save job to temporary file for use with fevalDistrDisk()
save([tDir int2str2(ind,10) '-in'],'job');
end
function r = jobLoad( tDir, ind, store )
% Helper: load job and delete temporary files from fevalDistrDisk()
f=[tDir int2str2(ind,10)];
if(store), r=load([f '-out']); r=r.r; else r=[]; end
fs={[f '-done'],[f '-in.mat'],[f '-out.mat']};
delete(fs{:}); pause(.1);
for i=1:3, k=0; while(exist(fs{i},'file')==2) %#ok<ALIGN>
warning('Waiting to delete %s.',fs{i}); %#ok<WNTAG>
delete(fs{i}); pause(5); k=k+1; if(k>12), break; end;
end; end
end
function msg = system2( cmd, show )
% Helper: wraps system() call
if(show), disp(cmd); end
[status,msg]=system(cmd); msg=msg(1:end-1);
if(status), error(msg); end
if(show), disp(msg); end
end
|
github
|
3arbouch/PersonDetection-master
|
medfilt1m.m
|
.m
|
PersonDetection-master/Source/toolbox/filters/medfilt1m.m
| 2,998 |
utf_8
|
a3733d27c60efefd57ada9d83ccbaa3d
|
function y = medfilt1m( x, r, z )
% One-dimensional adaptive median filtering with missing values.
%
% Applies a width s=2*r+1 one-dimensional median filter to vector x, which
% may contain missing values (elements equal to z). If x contains no
% missing values, y(j) is set to the median of x(j-r:j+r). If x contains
% missing values, y(j) is set to the median of x(j-R:j+R), where R is the
% smallest radius such that sum(valid(x(j-R:j+R)))>=s, i.e. the number of
% valid values in the window is at least s (a value x is valid x~=z). Note
% that the radius R is adaptive and can vary as a function of j.
%
% This function uses a modified version of medfilt1.m from Matlab's 'Signal
% Processing Toolbox'. Note that if x contains no missing values,
% medfilt1m(x) and medfilt1(x) are identical execpt at boundary regions.
%
% USAGE
% y = medfilt1m( x, r, [z] )
%
% INPUTS
% x - [nx1] length n vector with possible missing entries
% r - filter radius
% z - [NaN] element that represents missing entries
%
% OUTPUTS
% y - [nx1] filtered vector x
%
% EXAMPLE
% x=repmat((1:4)',1,5)'; x=x(:)'; x0=x;
% n=length(x); x(rand(n,1)>.8)=NaN;
% y = medfilt1m(x,2); [x0; x; y; x0-y]
%
% See also MODEFILT1, MEDFILT1
%
% Piotr's Computer Vision Matlab Toolbox Version 2.35
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% apply medfilt1 (standard median filter) to valid locations in x
if(nargin<3 || isempty(z)), z=NaN; end; x=x(:)'; n=length(x);
if(isnan(z)), valid=~isnan(x); else valid=x~=z; end; v=sum(valid);
if(v==0), y=repmat(z,1,n); return; end
if(v<2*r+1), y=repmat(median(x(valid)),1,n); return; end
y=medfilt1(x(valid),2*r+1);
% get radius R needed at each location j to span s=2r+1 valid values
% get start (a) and end (b) locations and map back to location in y
C=[0 cumsum(valid)]; s=2*r+1; R=find(C==s); R=R(1)-2; pos=zeros(1,n);
for j=1:n, R0=R;
R=R0-1; a=max(1,j-R); b=min(n,j+R);
if(C(b+1)-C(a)<s), R=R0; a=max(1,j-R); b=min(n,j+R);
if(C(b+1)-C(a)<s), R=R0+1; a=max(1,j-R); b=min(n,j+R); end
end
pos(j)=(C(b+1)+C(a+1))/2;
end
y=y(floor(pos));
end
function y = medfilt1( x, s )
% standard median filter (copied from medfilt1.m)
n=length(x); r=floor(s/2); indr=(0:s-1)'; indc=1:n;
ind=indc(ones(1,s),1:n)+indr(:,ones(1,n));
x0=x(ones(r,1))*0; X=[x0'; x'; x0'];
X=reshape(X(ind),s,n); y=median(X,1);
end
% function y = medfilt1( x, s )
% % standard median filter (slow)
% % get unique values in x
% [vals,disc,inds]=unique(x); m=length(vals); n=length(x);
% if(m>256), warning('x takes on large number of diff vals'); end %#ok<WNTAG>
% % create quantized representation [H(i,j)==1 iff x(j)==vals(i)]
% H=zeros(m,n); H(sub2ind2([m,n],[inds; 1:n]'))=1;
% % create histogram [H(i,j) is count of x(j-r:j+r)==vals(i)]
% H=localSum(H,[0 s],'same');
% % compute median for each j and map inds back to original vals
% [disc,inds]=max(cumsum(H,1)>s/2,[],1); y=vals(inds);
% end
|
github
|
3arbouch/PersonDetection-master
|
FbMake.m
|
.m
|
PersonDetection-master/Source/toolbox/filters/FbMake.m
| 6,692 |
utf_8
|
b625c1461a61485af27e490333350b4b
|
function FB = FbMake( dim, flag, show )
% Various 1D/2D/3D filterbanks (hardcoded).
%
% USAGE
% FB = FbMake( dim, flag, [show] )
%
% INPUTS
% dim - dimension
% flag - controls type of filterbank to create
% - if d==1
% 1: gabor filter bank for spatiotemporal stuff
% - if d==2
% 1: filter bank from Serge Belongie
% 2: 1st/2nd order DooG filters. Similar to Gabor filterbank.
% 3: similar to Laptev&Lindberg ICPR04
% 4: decent seperable steerable? filterbank
% 5: berkeley filterbank for textons papers
% 6: symmetric DOOG filters
% - if d==3
% 1: decent seperable steerable filterbank
% show - [0] figure to use for optional display
%
% OUTPUTS
%
% EXAMPLE
% FB = FbMake( 2, 1, 1 );
%
% See also FBAPPLY2D
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<3 || isempty(show) ); show=0; end
% create FB
switch dim
case 1
FB = FbMake1D( flag );
case 2
FB = FbMake2D( flag );
case 3
FB = FbMake3d( flag );
otherwise
error( 'dim must be 1 2 or 3');
end
% display
FbVisualize( FB, show );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function FB = FbMake1D( flag )
switch flag
case 1 %%% gabor filter bank for spatiotemporal stuff
omegas = 1 ./ [3 4 5 7.5 11];
sigmas = [3 4 5 7.5 11];
FB = FbMakegabor1D( 15, sigmas, omegas );
otherwise
error('none created.');
end
function FB = FbMakegabor1D( r, sigmas, omegas )
for i=1:length(omegas)
[feven,fodd]=filterGabor1d(r,sigmas(i),omegas(i));
if( i==1 ); FB=repmat(feven,[2*length(omegas) 1]); end
FB(i*2-1,:)=feven; FB(i*2,:)=fodd;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function FB = FbMake2D( flag )
switch flag
case 1 %%% filter bank from Berkeley / Serge Belongie
r=15;
FB = FbMakegabor( r, 6, 3, 3, sqrt(2) );
FB2 = FbMakeDOG( r, .6, 2.8, 4);
FB = cat(3, FB, FB2);
%FB = FB(:,:,1:2:36); %include only even symmetric filters
%FB = FB(:,:,2:2:36); %include only odd symmetric filters
case 2 %%% 1st/2nd order DooG filters. Similar to Gabor filterbank.
FB = FbMakeDooG( 15, 6, 3, 5, .5) ;
case 3 %%% similar to Laptev&Lindberg ICPR04
% Wierd filterbank of Gaussian derivatives at various scales
% Higher order filters probably not useful.
r = 9; dims=[2*r+1 2*r+1];
sigs = [.5 1 1.5 3]; % sigs = [1,1.5,2];
derivs = [];
%derivs = [ derivs; 0 0 ]; % 0th order
%derivs = [ derivs; 1 0; 0 1 ]; % first order
%derivs = [ derivs; 2 0; 0 2; 1 1 ]; % 2nd order
%derivs = [ derivs; 3 0; 0 3; 1 2; 2 1 ]; % 3rd order
%derivs = [ derivs; 4 0; 0 4; 1 3; 3 1; 2 2 ]; % 4th order
derivs = [ derivs; 0 1; 0 2; 0 3; 0 4; 0 5]; % 0n order
derivs = [ derivs; 1 0; 2 0; 3 0; 4 0; 5 0]; % n0 order
cnt=1; nderivs = size(derivs,1);
for s=1:length(sigs)
for i=1:nderivs
dG = filterDoog( dims, [sigs(s) sigs(s)], derivs(i,:), 0 );
if(s==1 && i==1); FB=repmat(dG,[1 1 length(sigs)*nderivs]); end
FB(:,:,cnt) = dG; cnt=cnt+1;
%dG = filterDoog( dims, [sigs(s)*3 sigs(s)], derivs(i,:), 0 );
%FB(:,:,cnt) = dG; cnt=cnt+1;
%dG = filterDoog( dims, [sigs(s) sigs(s)*3], derivs(i,:), 0 );
%FB(:,:,cnt) = dG; cnt=cnt+1;
end
end
case 4 % decent seperable steerable? filterbank
r = 9; dims=[2*r+1 2*r+1];
sigs = [.5 1.5 3];
derivs = [1 0; 0 1; 2 0; 0 2];
cnt=1; nderivs = size(derivs,1);
for s=1:length(sigs)
for i=1:nderivs
dG = filterDoog( dims, [sigs(s) sigs(s)], derivs(i,:), 0 );
if(s==1 && i==1); FB=repmat(dG,[1 1 length(sigs)*nderivs]); end
FB(:,:,cnt) = dG; cnt=cnt+1;
end
end
FB2 = FbMakeDOG( r, .6, 2.8, 4);
FB = cat(3, FB, FB2);
case 5 %%% berkeley filterbank for textons papers
FB = FbMakegabor( 7, 6, 1, 2, 2 );
case 6 %%% symmetric DOOG filters
FB = FbMakeDooGSym( 4, 2, [.5 1] );
otherwise
error('none created.');
end
function FB = FbMakegabor( r, nOrient, nScales, lambda, sigma )
% multi-scale even/odd gabor filters. Adapted from code by Serge Belongie.
cnt=1;
for m=1:nScales
for n=1:nOrient
[F1,F2]=filterGabor2d(r,sigma^m,lambda,180*(n-1)/nOrient);
if(m==1 && n==1); FB=repmat(F1,[1 1 nScales*nOrient*2]); end
FB(:,:,cnt)=F1; cnt=cnt+1; FB(:,:,cnt)=F2; cnt=cnt+1;
end
end
function FB = FbMakeDooGSym( r, nOrient, sigs )
% Adds symmetric DooG filters. These are similar to gabor filters.
cnt=1; dims=[2*r+1 2*r+1];
for s=1:length(sigs)
Fodd = -filterDoog( dims, [sigs(s) sigs(s)], [1 0], 0 );
Feven = filterDoog( dims, [sigs(s) sigs(s)], [2 0], 0 );
if(s==1); FB=repmat(Fodd,[1 1 length(sigs)*nOrient*2]); end
for n=1:nOrient
theta = 180*(n-1)/nOrient;
FB(:,:,cnt) = imrotate( Feven, theta, 'bil', 'crop' ); cnt=cnt+1;
FB(:,:,cnt) = imrotate( Fodd, theta, 'bil', 'crop' ); cnt=cnt+1;
end
end
function FB = FbMakeDooG( r, nOrient, nScales, lambda, sigma )
% 1st/2nd order DooG filters. Similar to Gabor filterbank.
% Defaults: nOrient=6, nScales=3, lambda=5, sigma=.5,
cnt=1; dims=[2*r+1 2*r+1];
for m=1:nScales
sigma = sigma * m^.7;
Fodd = -filterDoog( dims, [sigma lambda*sigma^.6], [1,0], 0 );
Feven = filterDoog( dims, [sigma lambda*sigma^.6], [2,0], 0 );
if(m==1); FB=repmat(Fodd,[1 1 nScales*nOrient*2]); end
for n=1:nOrient
theta = 180*(n-1)/nOrient;
FB(:,:,cnt) = imrotate( Feven, theta, 'bil', 'crop' ); cnt=cnt+1;
FB(:,:,cnt) = imrotate( Fodd, theta, 'bil', 'crop' ); cnt=cnt+1;
end
end
function FB = FbMakeDOG( r, sigmaStr, sigmaEnd, n )
% adds a serires of difference of Gaussian filters.
sigs = sigmaStr:(sigmaEnd-sigmaStr)/(n-1):sigmaEnd;
for s=1:length(sigs)
FB(:,:,s) = filterDog2d(r,sigs(s),2); %#ok<AGROW>
if( s==1 ); FB=repmat(FB,[1 1 length(sigs)]); end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function FB = FbMake3d( flag )
switch flag
case 1 % decent seperable steerable filterbank
r = 25; dims=[2*r+1 2*r+1 2*r+1];
sigs = [.5 1.5 3];
derivs = [0 0 1; 0 1 0; 1 0 0; 0 0 2; 0 2 0; 2 0 0];
cnt=1; nderivs = size(derivs,1);
for s=1:length(sigs)
for i=1:nderivs
dG = filterDoog( dims, repmat(sigs(s),[1 3]), derivs(i,:), 0 );
if(s==1 && i==1); FB=repmat(dG,[1 1 1 nderivs*length(sigs)]); end
FB(:,:,:,cnt) = dG; cnt=cnt+1;
end
end
otherwise
error('none created.');
end
|
github
|
3arbouch/PersonDetection-master
|
evaluateMultipleMethods.m
|
.m
|
PersonDetection-master/Source/PersonDetectionFinal/NeuralNetworks/evaluateMultipleMethods.m
| 1,493 |
utf_8
|
8b76479ee09e2a4dd2430c139ff5e7d0
|
% Automatically calls fastROC() to show multiple curves, one for each
% prediction vector provided.
%
% labels Nx1 vector
% predictions NxM vector, M being the number of predictions to show
%
% if showPlot == true => single plot with multiple curves is shown.
% legendNames is a cell list (optional) with the name to show for each
% prediction in the legend.
%
% Returns tprAtWP where each element is the tprAtWP of each prediction
% vector given as input.
%
function tprAtWP = evaluateMultipleMethods( labels, predictions, ...
showPlot, legendNames )
if nargin < 3
showPlot = false;
end
if nargin < 4
legendNames = [];
end
if size(labels,2) ~= 1
error('Labels must be Nx1');
end
if size(labels,1) ~= size(predictions,1)
error('labels and predictions must have same number of rows');
end
M = size(predictions,2);
% list of plotting styles
styles = {'r','b','k','m','g','r--', 'b--', 'k--','m--','g--'};
if showPlot && (M > length(styles))
error('Number of lines to show exceeds possible styles');
end
tprAtWP = zeros(M,1);
if showPlot
figure;
end
for i=1:M
tprAtWP(i) = fastROC( labels, predictions(:,i), showPlot, styles{i} );
if showPlot
hold on;
end
end
if showPlot && ~isempty(legendNames)
% add tprAtWP to legend names
for i=1:M
legendNames{i} = sprintf('%s: %.3f', legendNames{i}, tprAtWP(i));
end
legend( legendNames, 'Location', 'NorthWest' );
end
|
github
|
3arbouch/PersonDetection-master
|
evaluateMultipleMethodsKFolds.m
|
.m
|
PersonDetection-master/Source/PersonDetectionFinal/NeuralNetworks/evaluateMultipleMethodsKFolds.m
| 1,864 |
utf_8
|
76811cce8def3f43d15cf44ead9a1853
|
% Automatically calls fastROC() to show multiple curves, one for each
% prediction vector provided.
%
% labels Nx1 vector
% predictions NxM vector, M being the number of predictions to show
%
% if showPlot == true => single plot with multiple curves is shown.
% legendNames is a cell list (optional) with the name to show for each
% prediction in the legend.
%
% Returns tprAtWP where each element is the tprAtWP of each prediction
% vector given as input.
%
function [tprAtWP,auc,fpr,tpr] = evaluateMultipleMethodsKFolds( labels, predictions, ...
showPlot, legendNames,plotMeanValue, stylesNum )
if nargin < 3
showPlot = false;
end
if ~plotMeanValue
legendNames = [];
end
if size(labels,2) ~= 1
error('Labels must be Nx1');
end
if size(labels,1) ~= size(predictions,1)
error('labels and predictions must have same number of rows');
end
M = size(predictions,2);
% list of plotting styles
styles = {'r','b','g','m','k'};
shades = [1 0.9 0.9 ; 0.9 0.9 1; 0.9 1 0.9 ; 1 0.9 1 ; 0.9 0.9 0.9] ;
if showPlot && (M > length(styles))
error('Number of lines to show exceeds possible styles');
end
tprAtWP = zeros(M,1);
% if showPlot
% figure;
% end
for i=1:M
if(plotMeanValue)
[tprAtWP(i),auc,fpr,tpr] = fastROCKFold( labels, predictions(:,i), showPlot, styles{stylesNum}, 0, plotMeanValue,legendNames(1) );
else
[tprAtWP(i),auc,fpr,tpr]= fastROCKFold( labels, predictions(:,i), showPlot, styles{stylesNum}, shades(stylesNum,:), plotMeanValue,'' ) ;
end
if showPlot
hold on;
end
end
%
% if showPlot && ~isempty(legendNames) && plotMeanValue
% % add tprAtWP to legend names
% for i=1:M
% legendNames{i} = sprintf('%s: %.3f', legendNames{i}, tprAtWP(i));
% end
%
% legend( legendNames, 'Location', 'NorthWest' );
end
|
github
|
3arbouch/PersonDetection-master
|
evaluateMultipleMethodsForKFolds.m
|
.m
|
PersonDetection-master/Source/PersonDetectionFinal/NeuralNetworks/evaluateMultipleMethodsForKFolds.m
| 1,811 |
utf_8
|
60d21d9e720c02cef8283d2829f05f8d
|
% Automatically calls fastROC() to show multiple curves, one for each
% prediction vector provided.
% shows also the mean predictions over all the K folds
% labels Nx1 vector
% predictions NxM vector, M being the number of predictions to show
%
% if showPlot == true => single plot with multiple curves is shown.
% legendNames is a cell list (optional) with the name to show for each
% prediction in the legend.
%
% Returns tprAtWP where each element is the tprAtWP of each prediction
% vector given as input.
%
function TPRAverage = evaluateMultipleMethodsForKFolds( labels, predictions,meanPredictions,showPlot, legendNames )
if nargin < 3
showPlot = false;
end
if nargin < 4
legendNames = [];
end
if size(labels,2) ~= 1
error('Labels must be Nx1');
end
if size(labels,1) ~= size(meanPredictions,1)
error('labels and predictions must have same number of rows');
end
M = size(predictions,2);
N = size(meanPredictions,2) ;
% list of plotting styles
styles = {'r','b','g'};
shades = [1 0.7 0.7 ; 0.7 0.7 1; 0.7 1 0.7 ] ;
if showPlot && (M > length(styles))
error('Number of lines to show exceeds possible styles');
end
tprAtWP = zeros(M,N);
TPRAverage = zeroes(N,1) ;
if showPlot
figure;
end
for j=1:N
for i=1:M
tprAtWP(i,j) = fastROC( labels, predictions(:,i), showPlot, styles{j},shades(j,:), flase);
if showPlot
hold on;
end
end
TPRAverage(j) = fastROC( labels, meanPredictions(:,j), showPlot, styles{j},0, true) ;
if showPlot
hold on;
end
end
if showPlot && ~isempty(legendNames)
% add tprAtWP to legend names
for i=1:N
legendNames{i} = sprintf('%s: %.3f', legendNames{i}, TPRAverage(i));
end
legend( legendNames, 'Location', 'NorthWest' );
end
|
github
|
3arbouch/PersonDetection-master
|
splitFair.m
|
.m
|
PersonDetection-master/Source/PersonDetectionFinal/SVM/PersonDetection/splitFair.m
| 1,196 |
utf_8
|
213eae7350b86f58a8cf2db987255809
|
function [XTr, yTr, XTe, yTe] = splitFair( X,y, prop,s)
% split the data into train and test given a proportion
setSeed(s);
N = size(y,1);
% generate random indices
idx = randperm(N);
Ntr = floor(prop * N);
% select few as training and others as testing
idxTr = idx(1:Ntr);
idxTe = idx(Ntr+1:end);
% create train-test split
XTr = X(idxTr,:);
yTr = y(idxTr);
XTe = X(idxTe,:);
yTe = y(idxTe);
indicesOfNonFaces = find(yTr<0) ;
numberOfFaces = sum(yTr>0) ;
indices=generateIndices(indicesOfNonFaces, numberOfFaces) ;
ind= [find(yTr>0)' indices ] ;
XTr = XTr(ind,:) ;
yTr = yTr(ind,:)
sum(yTr>0)
sum(yTr<0)
end
function setSeed(seed)
% set seed
global RNDN_STATE RND_STATE
RNDN_STATE = randn('state');
randn('state',seed);
RND_STATE = rand('state');
%rand('state',seed);
rand('twister',seed);
end
function indicesNonFacesToTake= generateIndices(indicesNonFaces, numberToTake)
indicesNonFacesToTake= zeros(1,numberToTake) ;
for i=1:numberToTake
index = randi([1 length(indicesNonFaces)],1,1) ;
indicesNonFacesToTake(i) = indicesNonFaces(index) ;
indicesNonFaces(index) = [] ;
end
end
|
github
|
3arbouch/PersonDetection-master
|
split.m
|
.m
|
PersonDetection-master/Source/PersonDetectionFinal/SVM/PersonDetection/split.m
| 623 |
utf_8
|
1d182818178b64fc3af780057cf987a3
|
function [XTr, yTr, XTe, yTe] = split( X,y, prop,s)
% split the data into train and test given a proportion
setSeed(s);
N = size(y,1);
% generate random indices
idx = randperm(N);
Ntr = floor(prop * N);
% select few as training and others as testing
idxTr = idx(1:Ntr);
idxTe = idx(Ntr+1:end);
% create train-test split
XTr = X(idxTr,:);
yTr = y(idxTr);
XTe = X(idxTe,:);
yTe = y(idxTe);
end
function setSeed(seed)
% set seed
global RNDN_STATE RND_STATE
RNDN_STATE = randn('state');
randn('state',seed);
RND_STATE = rand('state');
%rand('state',seed);
rand('twister',seed);
end
|
github
|
3arbouch/PersonDetection-master
|
splitAndSubSample.m
|
.m
|
PersonDetection-master/Source/PersonDetectionFinal/SVM/PersonDetection/splitAndSubSample.m
| 755 |
utf_8
|
7b2b67aac6ba27d454c06485657dceb3
|
function [XTr, yTr, XTe, yTe] = splitNAdSubSample( X,y, prop,subSamplingRate,s)
% split the data into train and test given a proportion
setSeed(s);
N = size(y,1);
% generate random indices
idx = randperm(N);
Ntr = floor(prop * N);
% select few as training and others as testing
idxTr = idx(1:Ntr);
idxTe = idx(Ntr+1:end);
% create train-test split
XTr = X(idxTr,:);
yTr = y(idxTr);
XTe = X(idxTe,:);
yTe = y(idxTe);
indices = 1:subSamplingRate:size(XTr,2) ;
XTr = XTr(:,indices) ;
XTe = XTe(:,indices) ;
end
function setSeed(seed)
% set seed
global RNDN_STATE RND_STATE
RNDN_STATE = randn('state');
randn('state',seed);
RND_STATE = rand('state');
%rand('state',seed);
rand('twister',seed);
end
|
github
|
3arbouch/PersonDetection-master
|
test.m
|
.m
|
PersonDetection-master/Source/PersonDetectionFinal/SVM/PersonDetection/test.m
| 301 |
utf_8
|
955b4d4bf715a6608655fd538605fea3
|
function indicesNonFacesToTake= test(indicesNonFaces, numberToTake)
indicesNonFacesToTake= zeros(1,numberToTake) ;
for i=1:numberToTake
index = randi([1 length(indicesNonFaces)],1,1) ;
indicesNonFacesToTake(i) = indicesNonFaces(index) ;
indicesNonFaces(index) = [] ;
end
end
|
github
|
3arbouch/PersonDetection-master
|
myOctaveVersion.m
|
.m
|
PersonDetection-master/Source/DeepLearnToolbox-master/util/myOctaveVersion.m
| 169 |
utf_8
|
d4603482a968c496b66a4ed4e7c72471
|
% return OCTAVE_VERSION or 'undefined' as a string
function result = myOctaveVersion()
if isOctave()
result = OCTAVE_VERSION;
else
result = 'undefined';
end
|
github
|
3arbouch/PersonDetection-master
|
isOctave.m
|
.m
|
PersonDetection-master/Source/DeepLearnToolbox-master/util/isOctave.m
| 108 |
utf_8
|
4695e8d7c4478e1e67733cca9903f9ef
|
%detects if we're running Octave
function result = isOctave()
result = exist('OCTAVE_VERSION') ~= 0;
end
|
github
|
3arbouch/PersonDetection-master
|
makeLMfilters.m
|
.m
|
PersonDetection-master/Source/DeepLearnToolbox-master/util/makeLMfilters.m
| 1,895 |
utf_8
|
21950924882d8a0c49ab03ef0681b618
|
function F=makeLMfilters
% Returns the LML filter bank of size 49x49x48 in F. To convolve an
% image I with the filter bank you can either use the matlab function
% conv2, i.e. responses(:,:,i)=conv2(I,F(:,:,i),'valid'), or use the
% Fourier transform.
SUP=49; % Support of the largest filter (must be odd)
SCALEX=sqrt(2).^[1:3]; % Sigma_{x} for the oriented filters
NORIENT=6; % Number of orientations
NROTINV=12;
NBAR=length(SCALEX)*NORIENT;
NEDGE=length(SCALEX)*NORIENT;
NF=NBAR+NEDGE+NROTINV;
F=zeros(SUP,SUP,NF);
hsup=(SUP-1)/2;
[x,y]=meshgrid([-hsup:hsup],[hsup:-1:-hsup]);
orgpts=[x(:) y(:)]';
count=1;
for scale=1:length(SCALEX),
for orient=0:NORIENT-1,
angle=pi*orient/NORIENT; % Not 2pi as filters have symmetry
c=cos(angle);s=sin(angle);
rotpts=[c -s;s c]*orgpts;
F(:,:,count)=makefilter(SCALEX(scale),0,1,rotpts,SUP);
F(:,:,count+NEDGE)=makefilter(SCALEX(scale),0,2,rotpts,SUP);
count=count+1;
end;
end;
count=NBAR+NEDGE+1;
SCALES=sqrt(2).^[1:4];
for i=1:length(SCALES),
F(:,:,count)=normalise(fspecial('gaussian',SUP,SCALES(i)));
F(:,:,count+1)=normalise(fspecial('log',SUP,SCALES(i)));
F(:,:,count+2)=normalise(fspecial('log',SUP,3*SCALES(i)));
count=count+3;
end;
return
function f=makefilter(scale,phasex,phasey,pts,sup)
gx=gauss1d(3*scale,0,pts(1,:),phasex);
gy=gauss1d(scale,0,pts(2,:),phasey);
f=normalise(reshape(gx.*gy,sup,sup));
return
function g=gauss1d(sigma,mean,x,ord)
% Function to compute gaussian derivatives of order 0 <= ord < 3
% evaluated at x.
x=x-mean;num=x.*x;
variance=sigma^2;
denom=2*variance;
g=exp(-num/denom)/(pi*denom)^0.5;
switch ord,
case 1, g=-g.*(x/variance);
case 2, g=g.*((num-variance)/(variance^2));
end;
return
function f=normalise(f), f=f-mean(f(:)); f=f/sum(abs(f(:))); return
|
github
|
3arbouch/PersonDetection-master
|
caenumgradcheck.m
|
.m
|
PersonDetection-master/Source/DeepLearnToolbox-master/CAE/caenumgradcheck.m
| 3,618 |
utf_8
|
6c481fc15ab7df32e0f476514100141a
|
function cae = caenumgradcheck(cae, x, y)
epsilon = 1e-4;
er = 1e-6;
disp('performing numerical gradient checking...')
for i = 1 : numel(cae.o)
p_cae = cae; p_cae.c{i} = p_cae.c{i} + epsilon;
m_cae = cae; m_cae.c{i} = m_cae.c{i} - epsilon;
[m_cae, p_cae] = caerun(m_cae, p_cae, x, y);
d = (p_cae.L - m_cae.L) / (2 * epsilon);
e = abs(d - cae.dc{i});
if e > er
disp('OUTPUT BIAS numerical gradient checking failed');
disp(e);
disp(d / cae.dc{i});
keyboard
end
end
for a = 1 : numel(cae.a)
p_cae = cae; p_cae.b{a} = p_cae.b{a} + epsilon;
m_cae = cae; m_cae.b{a} = m_cae.b{a} - epsilon;
[m_cae, p_cae] = caerun(m_cae, p_cae, x, y);
d = (p_cae.L - m_cae.L) / (2 * epsilon);
% cae.dok{i}{a}(u) = d;
e = abs(d - cae.db{a});
if e > er
disp('BIAS numerical gradient checking failed');
disp(e);
disp(d / cae.db{a});
keyboard
end
for i = 1 : numel(cae.o)
for u = 1 : numel(cae.ok{i}{a})
p_cae = cae; p_cae.ok{i}{a}(u) = p_cae.ok{i}{a}(u) + epsilon;
m_cae = cae; m_cae.ok{i}{a}(u) = m_cae.ok{i}{a}(u) - epsilon;
[m_cae, p_cae] = caerun(m_cae, p_cae, x, y);
d = (p_cae.L - m_cae.L) / (2 * epsilon);
% cae.dok{i}{a}(u) = d;
e = abs(d - cae.dok{i}{a}(u));
if e > er
disp('OUTPUT KERNEL numerical gradient checking failed');
disp(e);
disp(d / cae.dok{i}{a}(u));
% keyboard
end
end
end
for i = 1 : numel(cae.i)
for u = 1 : numel(cae.ik{i}{a})
p_cae = cae;
m_cae = cae;
p_cae.ik{i}{a}(u) = p_cae.ik{i}{a}(u) + epsilon;
m_cae.ik{i}{a}(u) = m_cae.ik{i}{a}(u) - epsilon;
[m_cae, p_cae] = caerun(m_cae, p_cae, x, y);
d = (p_cae.L - m_cae.L) / (2 * epsilon);
% cae.dik{i}{a}(u) = d;
e = abs(d - cae.dik{i}{a}(u));
if e > er
disp('INPUT KERNEL numerical gradient checking failed');
disp(e);
disp(d / cae.dik{i}{a}(u));
end
end
end
end
disp('done')
end
function [m_cae, p_cae] = caerun(m_cae, p_cae, x, y)
m_cae = caeup(m_cae, x); m_cae = caedown(m_cae); m_cae = caebp(m_cae, y);
p_cae = caeup(p_cae, x); p_cae = caedown(p_cae); p_cae = caebp(p_cae, y);
end
%function checknumgrad(cae,what,x,y)
% epsilon = 1e-4;
% er = 1e-9;
%
% for i = 1 : numel(eval(what))
% if iscell(eval(['cae.' what]))
% checknumgrad(cae,[what '{' num2str(i) '}'], x, y)
% else
% p_cae = cae;
% m_cae = cae;
% eval(['p_cae.' what '(' num2str(i) ')']) = eval([what '(' num2str(i) ')']) + epsilon;
% eval(['m_cae.' what '(' num2str(i) ')']) = eval([what '(' num2str(i) ')']) - epsilon;
%
% m_cae = caeff(m_cae, x); m_cae = caedown(m_cae); m_cae = caebp(m_cae, y);
% p_cae = caeff(p_cae, x); p_cae = caedown(p_cae); p_cae = caebp(p_cae, y);
%
% d = (p_cae.L - m_cae.L) / (2 * epsilon);
% e = abs(d - eval(['cae.d' what '(' num2str(i) ')']));
% if e > er
% error('numerical gradient checking failed');
% end
% end
% end
%
% end
|
github
|
3arbouch/PersonDetection-master
|
evaluateMultipleMethods.m
|
.m
|
PersonDetection-master/Source/PersondetectionExC/evaluateMultipleMethods.m
| 1,493 |
utf_8
|
8b76479ee09e2a4dd2430c139ff5e7d0
|
% Automatically calls fastROC() to show multiple curves, one for each
% prediction vector provided.
%
% labels Nx1 vector
% predictions NxM vector, M being the number of predictions to show
%
% if showPlot == true => single plot with multiple curves is shown.
% legendNames is a cell list (optional) with the name to show for each
% prediction in the legend.
%
% Returns tprAtWP where each element is the tprAtWP of each prediction
% vector given as input.
%
function tprAtWP = evaluateMultipleMethods( labels, predictions, ...
showPlot, legendNames )
if nargin < 3
showPlot = false;
end
if nargin < 4
legendNames = [];
end
if size(labels,2) ~= 1
error('Labels must be Nx1');
end
if size(labels,1) ~= size(predictions,1)
error('labels and predictions must have same number of rows');
end
M = size(predictions,2);
% list of plotting styles
styles = {'r','b','k','m','g','r--', 'b--', 'k--','m--','g--'};
if showPlot && (M > length(styles))
error('Number of lines to show exceeds possible styles');
end
tprAtWP = zeros(M,1);
if showPlot
figure;
end
for i=1:M
tprAtWP(i) = fastROC( labels, predictions(:,i), showPlot, styles{i} );
if showPlot
hold on;
end
end
if showPlot && ~isempty(legendNames)
% add tprAtWP to legend names
for i=1:M
legendNames{i} = sprintf('%s: %.3f', legendNames{i}, tprAtWP(i));
end
legend( legendNames, 'Location', 'NorthWest' );
end
|
github
|
3arbouch/PersonDetection-master
|
evaluateMultipleMethods.m
|
.m
|
PersonDetection-master/Source/PersondetectionExC2/evaluateMultipleMethods.m
| 1,493 |
utf_8
|
8b76479ee09e2a4dd2430c139ff5e7d0
|
% Automatically calls fastROC() to show multiple curves, one for each
% prediction vector provided.
%
% labels Nx1 vector
% predictions NxM vector, M being the number of predictions to show
%
% if showPlot == true => single plot with multiple curves is shown.
% legendNames is a cell list (optional) with the name to show for each
% prediction in the legend.
%
% Returns tprAtWP where each element is the tprAtWP of each prediction
% vector given as input.
%
function tprAtWP = evaluateMultipleMethods( labels, predictions, ...
showPlot, legendNames )
if nargin < 3
showPlot = false;
end
if nargin < 4
legendNames = [];
end
if size(labels,2) ~= 1
error('Labels must be Nx1');
end
if size(labels,1) ~= size(predictions,1)
error('labels and predictions must have same number of rows');
end
M = size(predictions,2);
% list of plotting styles
styles = {'r','b','k','m','g','r--', 'b--', 'k--','m--','g--'};
if showPlot && (M > length(styles))
error('Number of lines to show exceeds possible styles');
end
tprAtWP = zeros(M,1);
if showPlot
figure;
end
for i=1:M
tprAtWP(i) = fastROC( labels, predictions(:,i), showPlot, styles{i} );
if showPlot
hold on;
end
end
if showPlot && ~isempty(legendNames)
% add tprAtWP to legend names
for i=1:M
legendNames{i} = sprintf('%s: %.3f', legendNames{i}, tprAtWP(i));
end
legend( legendNames, 'Location', 'NorthWest' );
end
|
github
|
weshu/HLx_Examples-master
|
db_cordic_atan2.m
|
.m
|
HLx_Examples-master/Math/atan2_cordic/M/db_cordic_atan2.m
| 1,600 |
utf_8
|
bba622d55a11b90855ec23ff82286f61
|
%/*
% Gain=1.647;
% mode 1: rotation; Rotates (x0,y0) by z0
% (xn,yn)=(cos(z0),sin(z0)) for (x0,y0)=(1,0)
% x[i+1] = x[i] - y[i] * d[i] * 2^(-1)
% y[i+1] = y[i] + x[i] * d[i] * 2^(-i)
% z[i+1] = z[i] - d[i] * atan(2^(-i))
% mode 0: vectoring; Rotates (x0,y0) to X-axis
% (xn,zn)=(r,theta)
% -PI/2<z0<PI/2
%*/
%function [xn, yn, zn] = db_cordic (mode, x0, y0, z0, N)
function [zn] = db_cordic (mode, x0, y0, z0, N)
%coord_t x, y, xp, yp;
%phase_t z, zp;
%bool xneg, yneg, dneg;
%uint6_t i;
%static const phase_t atan_2Mi[] = { #include "cordic_atan.h" };
I = [0 : N];
atan_2Mi = [atan(2.^(-I))];
quadrant = 0;
if ((x0>0) & (y0>0))
quadrant = 1;
elseif ((x0<0) & (y0>0))
quadrant = 2;
elseif ((x0<0) & (y0<0))
quadrant = 3;
elseif ((x0>0) & (y0<0))
quadrant = 4;
end
x=abs(x0);
y=abs(y0);
z=z0;
for i=0 : N
if (mode==1)
dneg = (z<0);
else
dneg = (y>0);
end
if (dneg)
xp = x + ( y/ 2^i);
yp = y - ( x / 2^i);
zp = z + atan_2Mi(i+1);
else
xp = x - ( y / 2^i);
yp = y + ( x / 2^i);
zp = z - atan_2Mi(i+1);
end
x = xp;
y = yp;
z = zp;
end
if (quadrant==1)
xn=x;
yn=y;
zn=z;
elseif (quadrant==2)
xn=x;
yn=-y;
zn=pi-z;
elseif (quadrant==3)
xn=-x;
yn=-y;
zn=-(pi-z);
elseif (quadrant==4)
xn=-x;
yn=-y;
zn=-z;
end
end
|
github
|
jjjjfrench/UW-UIOPS-master
|
read_binary_SEA_WMI.m
|
.m
|
UW-UIOPS-master/read_binary/read_binary_SEA_WMI.m
| 17,995 |
utf_8
|
a7bae0e57054c13b60c40dcf05a0e960
|
function read_binary_SEA_WMI(infilename,outfilename)
%% Function to decompress SEA raw files
% Need to double check the file format and code for each probes
% This only works for MC3E filed campaign
% * July 11, 2016, Created this new interface function, Wei Wu
starpos = find(infilename == '*',1,'last');
slashpos = find(infilename == '/',1,'last');
nWierdTotal = 0;
if ~isempty(starpos)
files = dir(infilename);
filenums = length(files);
filedir = infilename(1:slashpos);
else
filenums = 1;
end
for i = 1:filenums
if outfilename == '1'
outfilename = [infilename(1:slashpos),'DIMG.',infilename(slashpos+1:end)];
end
if filenums > 1
infilename = [filedir,files(i).name];
end
fid=fopen(infilename,'r','l');
infilename
%%% Updated for new MATLAB NETCDF interface
f = netcdf.create([outfilename, '.CIP.cdf'], 'clobber');
dimid0 = netcdf.defDim(f,'time',netcdf.getConstant('NC_UNLIMITED'));
dimid1 = netcdf.defDim(f,'ImgRowlen',8);
dimid2 = netcdf.defDim(f,'ImgBlocklen',1700);
varid0 = netcdf.defVar(f,'year','double',dimid0);
varid1 = netcdf.defVar(f,'month','double',dimid0);
varid2 = netcdf.defVar(f,'day','double',dimid0);
varid3 = netcdf.defVar(f,'hour','double',dimid0);
varid4 = netcdf.defVar(f,'minute','double',dimid0);
varid5 = netcdf.defVar(f,'second','double',dimid0);
varid6 = netcdf.defVar(f,'millisec','double',dimid0);
varid7 = netcdf.defVar(f,'wkday','double',dimid0);
varid8 = netcdf.defVar(f,'data','double',[dimid1 dimid2 dimid0]);
netcdf.endDef(f)
f1 = netcdf.create([outfilename, '.PIP.cdf'], 'clobber');
dimid01 = netcdf.defDim(f1,'time',netcdf.getConstant('NC_UNLIMITED'));
dimid11 = netcdf.defDim(f1,'ImgRowlen',8);
dimid21 = netcdf.defDim(f1,'ImgBlocklen',1700);
varid01 = netcdf.defVar(f1,'year','double',dimid01);
varid11 = netcdf.defVar(f1,'month','double',dimid01);
varid21 = netcdf.defVar(f1,'day','double',dimid01);
varid31 = netcdf.defVar(f1,'hour','double',dimid01);
varid41 = netcdf.defVar(f1,'minute','double',dimid01);
varid51 = netcdf.defVar(f1,'second','double',dimid01);
varid61 = netcdf.defVar(f1,'millisec','double',dimid01);
varid71 = netcdf.defVar(f1,'wkday','double',dimid01);
varid81 = netcdf.defVar(f1,'data','double',[dimid11 dimid21 dimid01]);
netcdf.endDef(f1)
kk=1;
kk1 =1;
wkday = 1;
datatemp = [0 0 0 0 0 0 0 0 0 0];
numFilename = 0;
nread =0;
endfile = 0;
% while feof(fid)==0 & kk <= 3000
while feof(fid)==0 & endfile == 0
[datalast,datatemp]=readDir(fid,datatemp);
doffset1 = -datatemp(2);
if datatemp(1)==999
nTagNext=1;
else
nTagNext=0;
end
while nTagNext==0
[datalast,datatemp]=readDir(fid,datatemp);
%if (datatemp(1)~=33000 & datatemp(3)==4098)
% datatemp(1)
%end
if datatemp(1)==33000 & datatemp(3)==4098
%datalast
%datatemp
[datalast,datatemp]=readDir(fid,datatemp);
%datatemp
ttt = readTime(fid);
year =ttt(1);
month=ttt(2);
day =ttt(3);
hour =ttt(4);
minute=ttt(5);
second=ttt(6);
millisec=ttt(7);
wkday=1;
data1 = fread(fid,4098,'uchar');
fseek(fid,-4150,0);
[datalast,datatemp]=readDir(fid,datatemp);
data = data1(1:4096);
% data=reshape(fread(fid,4096*8,'ubit1'),4096,8);
% b1 = [num2str(data(:,1)),num2str(data(:,2)),num2str(data(:,3)),num2str(data(:,4)),num2str(data(:,5)),...
% num2str(data(:,6)),num2str(data(:,7)),num2str(data(:,8))];
bytes=dec2hex(data,2);
kk;
i=1;
ii=1;
b1full=dec2bin(hex2dec(bytes(:,:)),8);
b2 = bin2dec(b1full(:,4:8));
while i<4096
b1 = b1full(i,:);
curi = i;
i=i+1;
if b1(3) == '1'
% i=i+1;
elseif b1(1) == '0' & b1(2) == '0'
% b2=bin2dec(b1(4:8));
for k=1:b2(curi)+1;
if i < length(bytes)
decomp(ii,:)=bytes(i,:);
else break
end
ii=ii+1;
i=i+1;
end
elseif b1(1) == '1' & b1(2) == '0'
% b2=bin2dec(b1(4:8));
for k=1:b2(curi)+1;
decomp(ii,:)='00';
ii=ii+1;
end
elseif b1(2) == '1' & b1(1) == '0'
% b2=bin2dec(b1(4:8));
for k=1:b2(curi)+1;
decomp(ii,:)='FF';
ii=ii+1;
end
else
kk;
end
end
found = 0;
i=1;
count=0;
while found == 0
if decomp(i)=='AA'
count=count+1;
else
count=0;
end
if count == 8
found=1;
dd=i+1:8:length(decomp)-7;
nWierd=0;
end
if i==length(decomp) % Add to avoid no 'AA' even though wierd to have no 'AA'...
found =1;
nWierd=1;
nWierdTotal =nWierdTotal +1;
end
i=i+1;
end
if nWierd ==0
%
% decomp_convert=[hex2dec(decomp(dd,:)),hex2dec(decomp(dd+1,:)),hex2dec(decomp(dd+2,:)),hex2dec(decomp(dd+3,:)),...
% hex2dec(decomp(dd+4,:)),hex2dec(decomp(dd+5,:)),hex2dec(decomp(dd+6,:)),hex2dec(decomp(dd+7,:))];
decomp_convert=[hex2dec(decomp(dd+7,:)),hex2dec(decomp(dd+6,:)),hex2dec(decomp(dd+5,:)),hex2dec(decomp(dd+4,:)),...
hex2dec(decomp(dd+3,:)),hex2dec(decomp(dd+2,:)),hex2dec(decomp(dd+1,:)),hex2dec(decomp(dd,:))];
k2=[decomp(dd,:),decomp(dd+1,:),decomp(dd+2,:),decomp(dd+3,:),decomp(dd+4,:),decomp(dd+5,:),decomp(dd+6,:),decomp(dd+7,:)];
% length_diff=length(decomp_convert) - length(handles.matrix(kk-1,:,:));
% matrix_size(kk)=length(decomp_convert);
% if length_diff > 0
% handles.matrix(1:kk-1,length(handles.matrix(kk-1,:,:)):length(decomp_convert),:)=-1;
% elseif length_diff < 0
% decomp_convert(length(decomp_convert):length(handles.matrix(kk-1,:,:)),:)=-1;
% end
if length(decomp_convert) < 1700
decomp_convert(length(decomp_convert):1700,:)=-1;
end
netcdf.putVar ( f, varid0, kk1-1, 1, year )
netcdf.putVar ( f, varid1, kk1-1, 1, month );
netcdf.putVar ( f, varid2, kk1-1, 1, day );
netcdf.putVar ( f, varid3, kk1-1, 1, hour );
netcdf.putVar ( f, varid4, kk1-1, 1, minute );
netcdf.putVar ( f, varid5, kk1-1, 1, second );
netcdf.putVar ( f, varid6, kk1-1, 1, millisec );
netcdf.putVar ( f, varid7, kk1-1, 1, wkday );
netcdf.putVar ( f, varid8, [0, 0, kk1-1], [8,1700,1], decomp_convert' );
kk1=kk1+1;
if mod(kk1,100) == 0
%kk1
%datestr(now)
end
end
elseif datatemp(1)==31000 & datatemp(3)==4098
%datalast
%datatemp
[datalast,datatemp]=readDir(fid,datatemp);
%datatemp
ttt = readTime(fid);
year =ttt(1);
month=ttt(2);
day =ttt(3);
hour =ttt(4);
minute=ttt(5);
second=ttt(6);
millisec=ttt(7);
wkday=1;
data1 = fread(fid,4098,'uchar');
fseek(fid,-4150,0);
[datalast,datatemp]=readDir(fid,datatemp);
data = data1(1:4096);
% data=reshape(fread(fid,4096*8,'ubit1'),4096,8);
% b1 = [num2str(data(:,1)),num2str(data(:,2)),num2str(data(:,3)),num2str(data(:,4)),num2str(data(:,5)),...
% num2str(data(:,6)),num2str(data(:,7)),num2str(data(:,8))];
bytes=dec2hex(data,2);
kk;
i=1;
ii=1;
b1full=dec2bin(hex2dec(bytes(:,:)),8);
b2 = bin2dec(b1full(:,4:8));
while i<4096
b1 = b1full(i,:);
curi = i;
i=i+1;
if b1(3) == '1'
% i=i+1;
elseif b1(1) == '0' & b1(2) == '0'
% b2=bin2dec(b1(4:8));
for k=1:b2(curi)+1;
if i < length(bytes)
decomp(ii,:)=bytes(i,:);
else break
end
ii=ii+1;
i=i+1;
end
elseif b1(1) == '1' & b1(2) == '0'
% b2=bin2dec(b1(4:8));
for k=1:b2(curi)+1;
decomp(ii,:)='00';
ii=ii+1;
end
elseif b1(2) == '1' & b1(1) == '0'
% b2=bin2dec(b1(4:8));
for k=1:b2(curi)+1;
decomp(ii,:)='FF';
ii=ii+1;
end
else
kk;
end
end
found = 0;
i=1;
count=0;
while found == 0
if decomp(i)=='AA'
count=count+1;
else
count=0;
end
if count == 8
found=1;
dd=i+1:8:length(decomp)-7;
nWierd=0;
end
if i==length(decomp) % Add to avoid no 'AA' even though wierd to have no 'AA'...
found =1;
nWierd=1;
nWierdTotal =nWierdTotal +1;
end
i=i+1;
end
if nWierd ==0
%
% decomp_convert=[hex2dec(decomp(dd,:)),hex2dec(decomp(dd+1,:)),hex2dec(decomp(dd+2,:)),hex2dec(decomp(dd+3,:)),...
% hex2dec(decomp(dd+4,:)),hex2dec(decomp(dd+5,:)),hex2dec(decomp(dd+6,:)),hex2dec(decomp(dd+7,:))];
decomp_convert=[hex2dec(decomp(dd+7,:)),hex2dec(decomp(dd+6,:)),hex2dec(decomp(dd+5,:)),hex2dec(decomp(dd+4,:)),...
hex2dec(decomp(dd+3,:)),hex2dec(decomp(dd+2,:)),hex2dec(decomp(dd+1,:)),hex2dec(decomp(dd,:))];
k2=[decomp(dd,:),decomp(dd+1,:),decomp(dd+2,:),decomp(dd+3,:),decomp(dd+4,:),decomp(dd+5,:),decomp(dd+6,:),decomp(dd+7,:)];
% length_diff=length(decomp_convert) - length(handles.matrix(kk-1,:,:));
% matrix_size(kk)=length(decomp_convert);
% if length_diff > 0
% handles.matrix(1:kk-1,length(handles.matrix(kk-1,:,:)):length(decomp_convert),:)=-1;
% elseif length_diff < 0
% decomp_convert(length(decomp_convert):length(handles.matrix(kk-1,:,:)),:)=-1;
% end
if length(decomp_convert) < 1700
decomp_convert(length(decomp_convert):1700,:)=-1;
end
netcdf.putVar ( f1, varid0, kk-1, 1, year )
netcdf.putVar ( f1, varid1, kk-1, 1, month );
netcdf.putVar ( f1, varid2, kk-1, 1, day );
netcdf.putVar ( f1, varid3, kk-1, 1, hour );
netcdf.putVar ( f1, varid4, kk-1, 1, minute );
netcdf.putVar ( f1, varid5, kk-1, 1, second );
netcdf.putVar ( f1, varid6, kk-1, 1, millisec );
netcdf.putVar ( f1, varid7, kk-1, 1, wkday );
netcdf.putVar ( f1, varid8, [0, 0, kk-1], [8,1700,1], decomp_convert' );
kk=kk+1;
if mod(kk,100) == 0
%kk
%datestr(now)
end
end
elseif datatemp(1)==5000 && datatemp(3)==123455 %4096
[datalast,datatemp]=readDir(fid,datatemp);
[datalast,datatemp]=readDir(fid,datatemp);
[datalast,datatemp]=readDir(fid,datatemp);
[datalast,datatemp]=readDir(fid,datatemp);
[datalast,datatemp]=readDir(fid,datatemp);
ttt = readTime(fid);
year =ttt(1);
month=ttt(2);
day =ttt(3);
hour =ttt(4);
minute=ttt(5);
second=ttt(6);
millisec=ttt(7);
wkday=1;
%dataother = fread(fid,14,'uchar');
temp0011 = fread(fid,1,'int16');
temp0012 = fread(fid,1,'int16');
fread(fid,10,'char');
% temp003 = fread(fid,1,'char');
% temp004 = fread(fid,1,'short');
% temp003/temp0011*temp0012*2*0.001
% temp002*25*0.000001
data1 = fread(fid,4096,'uchar');
fseek(fid,-4162,0);
[datalast,datatemp]=readDir(fid,datatemp);
tas=temp0011/temp0012*50*1000*25*0.000001;
datafinal = reshape(data1,4,1024);
temp1234 = datafinal(1,:);
datafinal(1,:)=datafinal(4,:);
datafinal(4,:)=temp1234;
temp1234 = datafinal(2,:);
datafinal(2,:)=datafinal(3,:);
datafinal(3,:)=temp1234;
netcdf.putVar ( f1, varid01, kk-1, 1, year )
netcdf.putVar ( f1, varid11, kk-1, 1, month );
netcdf.putVar ( f1, varid21, kk-1, 1, day );
netcdf.putVar ( f1, varid31, kk-1, 1, hour );
netcdf.putVar ( f1, varid41, kk-1, 1, minute );
netcdf.putVar ( f1, varid51, kk-1, 1, second );
netcdf.putVar ( f1, varid61, kk-1, 1, millisec );
netcdf.putVar ( f1, varid71, kk-1, 1, wkday );
netcdf.putVar ( f1, varid91, kk-1, 1, tas );
netcdf.putVar ( f1, varid81, [0, 0, kk-1], [4,1024,1], datafinal );
kk=kk+1;
if mod(kk,100) == 0
kk
datestr(now)
end
end
clear decomp dd k2 b1 b2
if datatemp(1)==999
doffset2 = datatemp(2);
nTagNext = 1;
fseek(fid,doffset2+doffset1,0);
end
end
for j=1:16
bb=fread(fid,1,'int8');
if feof(fid) == 1
endfile=1;
break
end
end
fseek(fid,-16,'cof');
end
end
fclose(fid);
% close(f);
netcdf.close(f); % New interface by Will
netcdf.close(f1); % New interface by Will
nWierdTotal
end
function [ldata,tdata]=readDir(fid,tdata)
tagNumber=fread(fid,1,'uint16');
dataOffset=fread(fid,1,'uint16');
numberBytes=fread(fid,1,'uint16');
samples=fread(fid,1,'uint16');
bytesPerSample=fread(fid,1,'uint16');
type=fread(fid,1,'uint8');
param1=fread(fid,1,'uint8');
param2=fread(fid,1,'uint8');
param3=fread(fid,1,'uint8');
address=fread(fid,1,'uint16');
ldata = tdata;
tdata = [tagNumber dataOffset numberBytes samples bytesPerSample type param1 param2 param3 address];
end
function time=readTime(fid)
for i=1:2
year=fread(fid,1,'uint16');
month=fread(fid,1,'uint16');
day=fread(fid,1,'uint16');
hour=fread(fid,1,'uint16');
minute=fread(fid,1,'uint16');
second=fread(fid,1,'uint16');
fracsec=fread(fid,1,'uint16');
maxfreq=fread(fid,1,'uint16');
bls=fread(fid,1,'uint16');
time=[year month day hour minute second fracsec maxfreq bls];
end
end
function readTable(fid)
filename = fread(fid,8,'uint8');
filename = char(filename);
filename=filename';
tfiles = fread(fid,datalast(3),'uint8');
abc = char(tfiles);
abc'
end
|
github
|
jjjjfrench/UW-UIOPS-master
|
read_binary_SPEC.m
|
.m
|
UW-UIOPS-master/read_binary/read_binary_SPEC.m
| 12,505 |
utf_8
|
a0c18ab97bc92b21845f9077e7bcec21
|
function read_binary_SPEC(infilename,outfilename)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Read the raw base*.2DS file, and then write into NETCDF file
%% Follow the SPEC manual
%% by Will Wu, 08/01/2014
%%
%% Changed file naming conventions for UW use. Updated to use NETCDF4.
%% by Adam Majewski, 10/31/2016
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
starpos = find(infilename == '*',1,'last');
slashpos = find(infilename == '/',1,'last');
if ~isempty(starpos) || outfilename == '1'
files = dir(infilename);
filenums = length(files);
filedir = infilename(1:slashpos);
else
filenums = 1;
end
for i = 1:filenums
if filenums > 1 || ~isempty(starpos)
infilename = [filedir,files(i).name];
end
if outfilename == '1'
%slashpos = find(infilename == '.',1,'last');
outfilename = [filedir,'DIMG.',files(i).name];
end
outfilename1=[outfilename, '.H.cdf'];
outfilename2=[outfilename, '.V.cdf'];
fid=fopen(infilename,'r','l');
%cmode = netcdf.getConstant('NETCDF4');
%cmode = bitor(cmode,netcdf.getConstant('CLOBBER'));
%f = netcdf.create(outfilename1,cmode);
f = netcdf.create(outfilename1, 'clobber');
dimid0 = netcdf.defDim(f,'time',netcdf.getConstant('NC_UNLIMITED'));
dimid1 = netcdf.defDim(f,'ImgRowlen',8);
dimid2 = netcdf.defDim(f,'ImgBlocklen',1700);
varid0 = netcdf.defVar(f,'year','short',dimid0);
varid1 = netcdf.defVar(f,'month','byte',dimid0);
varid2 = netcdf.defVar(f,'day','byte',dimid0);
varid3 = netcdf.defVar(f,'hour','byte',dimid0);
varid4 = netcdf.defVar(f,'minute','byte',dimid0);
varid5 = netcdf.defVar(f,'second','byte',dimid0);
varid6 = netcdf.defVar(f,'millisec','short',dimid0);
varid7 = netcdf.defVar(f,'wkday','byte',dimid0);
varid8 = netcdf.defVar(f,'data','int',[dimid1 dimid2 dimid0]);
netcdf.endDef(f)
%f1 = netcdf.create(outfilename2, cmode);
f1 = netcdf.create(outfilename2, 'clobber');
dimid01 = netcdf.defDim(f1,'time',netcdf.getConstant('NC_UNLIMITED'));
dimid11 = netcdf.defDim(f1,'ImgRowlen',8);
dimid21 = netcdf.defDim(f1,'ImgBlocklen',1700);
varid01 = netcdf.defVar(f1,'year','short',dimid01);
varid11 = netcdf.defVar(f1,'month','byte',dimid01);
varid21 = netcdf.defVar(f1,'day','byte',dimid01);
varid31 = netcdf.defVar(f1,'hour','byte',dimid01);
varid41 = netcdf.defVar(f1,'minute','byte',dimid01);
varid51 = netcdf.defVar(f1,'second','byte',dimid01);
varid61 = netcdf.defVar(f1,'millisec','short',dimid01);
varid71 = netcdf.defVar(f1,'wkday','byte',dimid01);
varid81 = netcdf.defVar(f1,'data','int',[dimid11 dimid21 dimid01]);
netcdf.endDef(f1)
kk1=1;
kk2=1;
endfile = 0;
nNext=1;
dataprev=zeros(2048,1);
%fseek(fid,4114*233191,'bof');
while feof(fid)==0 && endfile == 0
%tic
[year,month, wkday,day, hour, minute, second, millisec, data, discard]=readRecord(fid);
timebuffer = [year,month,day, hour, minute, second, millisec]
%fprintf(formatSpec,A1,A2)
[year1,month1, wkday1,day1, hour1, minute1, second1, millisec1, data1, discard1]=readRecord(fid);
%fseek(fid,-4114,'cof');
datan=[data' data1'];
datan=datan';
[imgH, imgV, nNext]=get_img(datan, hour*10000+minute*100+second+millisec/1000,outfilename);
sizeimg= size(imgH);
if sizeimg(2)>1700
imgH=imgH(:,1:1700);
sizeimg(2)
end
sizeimg= size(imgV);
if sizeimg(2)>1700
imgV=imgV(:,1:1700);
sizeimg(2)
end
if sum(sum(imgH))~=0
for mmm=1:8
img1(mmm,1:1700)=sixteen2int(imgH((mmm-1)*16+1:mmm*16,1:1700));
end
netcdf.putVar ( f, varid0, kk1-1, 1, year );
netcdf.putVar ( f, varid1, kk1-1, 1, month );
netcdf.putVar ( f, varid2, kk1-1, 1, day );
netcdf.putVar ( f, varid3, kk1-1, 1, hour );
netcdf.putVar ( f, varid4, kk1-1, 1, minute );
netcdf.putVar ( f, varid5, kk1-1, 1, second );
netcdf.putVar ( f, varid6, kk1-1, 1, millisec );
netcdf.putVar ( f, varid7, kk1-1, 1, wkday );
netcdf.putVar ( f, varid8, [0, 0, kk1-1], [8,1700,1], img1 );
kk1=kk1+1;
if mod(kk1,1000) == 0
['kk1=' num2str(kk1) ', ' datestr(now)]
end
end
if sum(sum(imgV))~=0
for mmm=1:8
img2(mmm,1:1700)=sixteen2int(imgV((mmm-1)*16+1:mmm*16,1:1700));
end
netcdf.putVar ( f1, varid01, kk2-1, 1, year );
netcdf.putVar ( f1, varid11, kk2-1, 1, month );
netcdf.putVar ( f1, varid21, kk2-1, 1, day );
netcdf.putVar ( f1, varid31, kk2-1, 1, hour );
netcdf.putVar ( f1, varid41, kk2-1, 1, minute );
netcdf.putVar ( f1, varid51, kk2-1, 1, second );
netcdf.putVar ( f1, varid61, kk2-1, 1, millisec );
netcdf.putVar ( f1, varid71, kk2-1, 1, wkday );
netcdf.putVar ( f1, varid81, [0, 0, kk2-1], [8,1700,1], img2 );
kk2=kk2+1;
if mod(kk2,1000) == 0
['kk2=' num2str(kk2) ', ' datestr(now)]
end
end
%for j=1:4115
bb=fread(fid,1,'int8');
if feof(fid) == 1
endfile=1;
break
end
%end
fseek(fid,-4115,'cof');
%kk
%ftell(fid)
%toc
end
netcdf.close(f);
netcdf.close(f1);
end
fclose(fid);
end
function [year,month, wkday,day, hour, minute, second, millisec, data, discard]=readRecord(fid)
year=fread(fid,1,'uint16');
month=fread(fid,1,'uint16');
wkday=fread(fid,1,'uint16');
day=fread(fid,1,'uint16');
hour=fread(fid,1,'uint16');
minute=fread(fid,1,'uint16');
second=fread(fid,1,'uint16');
millisec=fread(fid,1,'uint16');
data = fread(fid,2048,'uint16');
discard=fread(fid,1,'uint16');
end
function [imgH, imgV, nNext]=get_img(buf, timehhmmss,outfilename)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Decompress the image
%% Follow the SPEC manual
%% by Will Wu, 06/20/2013
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
imgH=zeros(128,1700);
imgV=zeros(128,1700);
iSlice=0;
iii=1;
while iii<=2048
if 12883==buf(iii) %'0011001001010011'
nH=bitand(buf(iii+1), 4095); %bin2dec('0000111111111111'));
bHTiming=bitand(buf(iii+1), 4096); %bin2dec('0001000000000000'))/2^13;
nV=bitand(buf(iii+2), 4095); %bin2dec('0000111111111111'));
bVTiming=bitand(buf(iii+2), 4096); %bin2dec('0001000000000000'))/2^13;
PC = buf(iii+3);
nS = buf(iii+4);
NHWord=buf(iii+1);
NVWord=buf(iii+2);
myformatNV = '%f, %d\n';
fid = fopen([outfilename, '.NV.csv'],'a');
fprintf(fid, myformatNV, [timehhmmss buf(iii+2)]);
fclose(fid);
if nH~=0 && nV~=0
system(['echo ' num2str(nH) ' ' num2str(nV) ' >> output.txt']);
end
iii=iii+5;
if bHTiming~=0 || bVTiming~=0
iii=iii+nH+nV;
elseif nH~=0
jjj=1;
kkk=0;
while jjj<=nS && kkk<nH-2 % Last two slice is time
aa=bitand(buf(iii+kkk),16256)/2^7; %bin2dec('0011111110000000')
bb=bitand(buf(iii+kkk),127); %bin2dec('0000000001111111')
imgH(min(128,bb+1):min(aa+bb,128),iSlice+jjj)=1;
bBase=min(aa+bb,128);
kkk=kkk+1;
while( bitand(buf(iii+kkk),16384)==0 && kkk<nH-2) % bin2dec('1000000000000000')
aa=bitand(buf(iii+kkk),16256)/2^7;
bb=bitand(buf(iii+kkk),127);
imgH(min(128,bBase+bb+1):min(bBase+aa+bb,128),iSlice+jjj)=1;
bBase=min(bBase+aa+bb,128);
kkk=kkk+1;
end
jjj=jjj+1;
end
iSlice=iSlice+nS+2;
imgH(:,iSlice-1)='10101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010';
imgH(:,iSlice-1)=imgH(:,iSlice-1)-48;
imgH(:,iSlice)=1;
tParticle=buf(iii+nH-2)*2^16+buf(iii+nH-1);
imgH(:,iSlice)=dec2bin(tParticle,128)-48;
imgH(97:128,iSlice)=dec2bin(tParticle,32)-48;
imgH(49:64,iSlice)=dec2bin(NHWord,16)-48;
imgH(65:80,iSlice)=dec2bin(PC,16)-48;
imgH(81:96,iSlice)=dec2bin(nS,16)-48;
iii=iii+nH;
elseif nV~=0
jjj=1;
kkk=0;
while jjj<=nS && kkk<nV-2 % Last two slice is time
aa=bitand(buf(iii+kkk),16256)/2^7; %bin2dec('0011111110000000')
bb=bitand(buf(iii+kkk),127); %bin2dec('0000000001111111')
imgV(min(128,bb+1):min(aa+bb,128),iSlice+jjj)=1;
bBase=min(aa+bb,128);
kkk=kkk+1;
while( bitand(buf(iii+kkk),16384)==0 && kkk<nV-2) % bin2dec('1000000000000000')
aa=bitand(buf(iii+kkk),16256)/2^7;
bb=bitand(buf(iii+kkk),127);
imgV(min(128,bBase+bb+1):min(bBase+aa+bb,128),iSlice+jjj)=1;
bBase=min(bBase+aa+bb,128);
kkk=kkk+1;
end
jjj=jjj+1;
end
iSlice=iSlice+nS+2;
imgV(:,iSlice-1)='10101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010';
imgV(:,iSlice-1)=imgV(:,iSlice-1)-48;
imgV(:,iSlice)=1;
tParticle=buf(iii+nV-2)*2^16+buf(iii+nV-1);
imgV(:,iSlice)=dec2bin(tParticle,128)-48;
imgV(97:128,iSlice)=dec2bin(tParticle,32)-48;
imgV(49:64,iSlice)=dec2bin(NVWord,16)-48;
imgV(65:80,iSlice)=dec2bin(PC,16)-48;
imgV(81:96,iSlice)=dec2bin(nS,16)-48;
iii=iii+nV;
end
elseif 18507==buf(iii)
tas = typecast( uint32(bin2dec([dec2bin(buf(iii-1+50),16) dec2bin(buf(iii-1+51),16)])) ,'single');
time = buf(iii-1+52)*2^16+buf(iii-1+53);
nStereo = buf(iii-1+41);
nTWM = buf(iii-1+42);
nSCM = buf(iii-1+43);
nHOL = buf(iii-1+44);
nVOL = buf(iii-1+45);
nVPD = buf(iii-1+34);
nHPD = buf(iii-1+35);
myformat1 = '%f, %f, %f, %d, %d, %d, %d, %d, %d\n';
fid = fopen([outfilename, '.tas.csv'],'a');
fprintf(fid, myformat1, [timehhmmss tas time nTWM nSCM nHOL nVOL nVPD nHPD]);
fclose(fid);
iii = iii + 53;
elseif 19787==buf(iii)
timeWord = buf(iii-1+2)*2^16+buf(iii-1+3);
MaskBits = [buf(iii-1+4:iii-1+19)]';
timeStart = buf(iii-1+20)*2^16+buf(iii-1+21);
timeEnd = buf(iii-1+22)*2^16+buf(iii-1+23);
myformat2 = '%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d \n';
fid = fopen([outfilename, '.MK.csv'],'a');
fprintf(fid, myformat2, [timeWord MaskBits timeStart timeEnd]);
fclose(fid);
iii = iii + 23;
else
iii=iii+1;
%disp(['Nowhere, move foreward...', num2str(iii)]);
end
end
nNext=iii-2048;
end
function intres=sixteen2int(original)
intres=zeros(1,1700);
for i=1:16
temp=original(i,:)*2^(16-i);
intres=intres+temp;
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.