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
|
sabbiu/ObjectDetection-master
|
vl_click.m
|
.m
|
ObjectDetection-master/Project-GUI/vlfeat-0.9.20/toolbox/plotop/vl_click.m
| 2,661 |
utf_8
|
6982e869cf80da57fdf68f5ebcd05a86
|
function P = vl_click(N,varargin) ;
% VL_CLICK Click a point
% P=VL_CLICK() let the user click a point in the current figure and
% returns its coordinates in P. P is a two dimensiona vectors where
% P(1) is the point X-coordinate and P(2) the point Y-coordinate. The
% user can abort the operation by pressing any key, in which case the
% empty matrix is returned.
%
% P=VL_CLICK(N) lets the user select N points in a row. The user can
% stop inserting points by pressing any key, in which case the
% partial list is returned.
%
% VL_CLICK() accepts the following options:
%
% PlotMarker:: [0]
% Plot a marker as points are selected. The markers are deleted on
% exiting the function.
%
% See also: VL_CLICKPOINT(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
plot_marker = 0 ;
for k=1:2:length(varargin)
switch lower(varargin{k})
case 'plotmarker'
plot_marker = varargin{k+1} ;
otherwise
error(['Uknown option ''', varargin{k}, '''.']) ;
end
end
if nargin < 1
N=1;
end
% --------------------------------------------------------------------
% Do job
% --------------------------------------------------------------------
fig = gcf ;
is_hold = ishold ;
hold on ;
bhandler = get(fig,'WindowButtonDownFcn') ;
khandler = get(fig,'KeyPressFcn') ;
pointer = get(fig,'Pointer') ;
set(fig,'WindowButtonDownFcn',@click_handler) ;
set(fig,'KeyPressFcn',@key_handler) ;
set(fig,'Pointer','crosshair') ;
P=[] ;
h=[] ;
data.exit=0;
guidata(fig,data) ;
while size(P,2) < N
uiwait(fig) ;
data = guidata(fig) ;
if(data.exit)
break ;
end
P = [P data.P] ;
if( plot_marker )
h=[h plot(data.P(1),data.P(2),'rx')] ;
end
end
if ~is_hold
hold off ;
end
if( plot_marker )
pause(.1);
delete(h) ;
end
set(fig,'WindowButtonDownFcn',bhandler) ;
set(fig,'KeyPressFcn',khandler) ;
set(fig,'Pointer',pointer) ;
% ====================================================================
function click_handler(obj,event)
% --------------------------------------------------------------------
data = guidata(gcbo) ;
P = get(gca, 'CurrentPoint') ;
P = [P(1,1); P(1,2)] ;
data.P = P ;
guidata(obj,data) ;
uiresume(gcbo) ;
% ====================================================================
function key_handler(obj,event)
% --------------------------------------------------------------------
data = guidata(gcbo) ;
data.exit = 1 ;
guidata(obj,data) ;
uiresume(gcbo) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_pr.m
|
.m
|
ObjectDetection-master/Project-GUI/vlfeat-0.9.20/toolbox/plotop/vl_pr.m
| 9,138 |
utf_8
|
c7fe6832d2b6b9917896810c52a05479
|
function [recall, precision, info] = vl_pr(labels, scores, varargin)
%VL_PR Precision-recall curve.
% [RECALL, PRECISION] = VL_PR(LABELS, SCORES) computes the
% precision-recall (PR) curve. LABELS are the ground truth labels,
% greather than zero for a positive sample and smaller than zero for
% a negative one. SCORES are the scores of the samples obtained from
% a classifier, where lager scores should correspond to positive
% samples.
%
% Samples are ranked by decreasing scores, starting from rank 1.
% PRECISION(K) and RECALL(K) are the precison and recall when
% samples of rank smaller or equal to K-1 are predicted to be
% positive and the remaining to be negative. So for example
% PRECISION(3) is the percentage of positive samples among the two
% samples with largest score. PRECISION(1) is the precision when no
% samples are predicted to be positive and is conventionally set to
% the value 1.
%
% Set to zero the lables of samples that should be ignored in the
% evaluation. Set to -INF the scores of samples which are not
% retrieved. If there are samples with -INF score, then the PR curve
% may have maximum recall smaller than 1, unless the INCLUDEINF
% option is used (see below). The options NUMNEGATIVES and
% NUMPOSITIVES can be used to add additional surrogate samples with
% -INF score (see below).
%
% [RECALL, PRECISION, INFO] = VL_PR(...) returns an additional
% structure INFO with the following fields:
%
% info.auc::
% The area under the precision-recall curve. If the INTERPOLATE
% option is set to FALSE, then trapezoidal interpolation is used
% to integrate the PR curve. If the INTERPOLATE option is set to
% TRUE, then the curve is piecewise constant and no other
% approximation is introduced in the calculation of the area. In
% the latter case, INFO.AUC is the same as INFO.AP.
%
% info.ap::
% Average precision as defined by TREC. This is the average of the
% precision observed each time a new positive sample is
% recalled. In this calculation, any sample with -INF score
% (unless INCLUDEINF is used) and any additional positive induced
% by NUMPOSITIVES has precision equal to zero. If the INTERPOLATE
% option is set to true, the AP is computed from the interpolated
% precision and the result is the same as INFO.AUC. Note that AP
% as defined by TREC normally does not use interpolation [1].
%
% info.ap_interp_11::
% 11-points interpolated average precision as defined by TREC.
% This is the average of the maximum precision for recall levels
% greather than 0.0, 0.1, 0.2, ..., 1.0. This measure was used in
% the PASCAL VOC challenge up to the 2008 edition.
%
% info.auc_pa08::
% Deprecated. It is the same of INFO.AP_INTERP_11.
%
% VL_PR(...) with no output arguments plots the PR curve in the
% current axis.
%
% VL_PR() accepts the following options:
%
% Interpolate:: false
% If set to true, use interpolated precision. The interpolated
% precision is defined as the maximum precision for a given recall
% level and onwards. Here it is implemented as the culumative
% maximum from low to high scores of the precision.
%
% NumPositives:: []
% NumNegatives:: []
% If set to a number, pretend that LABELS contains this may
% positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be
% smaller than the actual number of positive/negative entrires in
% LABELS. The additional positive/negative labels are appended to
% the end of the sequence, as if they had -INF scores (not
% retrieved). This is useful to evaluate large retrieval systems
% for which one stores ony a handful of top results for efficiency
% reasons.
%
% IncludeInf:: false
% If set to true, data with -INF score SCORES is included in the
% evaluation and the maximum recall is 1 even if -INF scores are
% present. This option does not include any additional positive or
% negative data introduced by specifying NUMPOSITIVES and
% NUMNEGATIVES.
%
% Stable:: false
% If set to true, RECALL and PRECISION are returned in the same order
% of LABELS and SCORES rather than being sorted by decreasing
% score (increasing recall). Samples with -INF scores are assigned
% RECALL and PRECISION equal to NaN.
%
% NormalizePrior:: []
% If set to a scalar, reweights positive and negative labels so
% that the fraction of positive ones is equal to the specified
% value. This computes the normalised PR curves of [2]
%
% About the PR curve::
% This section uses the same symbols used in the documentation of
% the VL_ROC() function. In addition to those quantities, define:
%
% PRECISION(S) = TP(S) / (TP(S) + FP(S))
% RECALL(S) = TPR(S) = TP(S) / P
%
% The precision is the fraction of positivie predictions which are
% correct, and the recall is the fraction of positive labels that
% have been correctly classified (recalled). Notice that the recall
% is also equal to the true positive rate for the ROC curve (see
% VL_ROC()).
%
% REFERENCES:
% [1] C. D. Manning, P. Raghavan, and H. Schutze. An Introduction to
% Information Retrieval. Cambridge University Press, 2008.
% [2] D. Hoiem, Y. Chodpathumwan, and Q. Dai. Diagnosing error in
% object detectors. In Proc. ECCV, 2012.
%
% See also VL_ROC(), VL_HELP().
% Author: Andrea Vedaldi
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
% TP and FP are the vectors of true positie and false positve label
% counts for decreasing scores, P and N are the total number of
% positive and negative labels. Note that if certain options are used
% some labels may actually not be stored explicitly by LABELS, so P+N
% can be larger than the number of element of LABELS.
[tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ;
opts.stable = false ;
opts.interpolate = false ;
opts.normalizePrior = [] ;
opts = vl_argparse(opts,varargin) ;
% compute precision and recall
small = 1e-10 ;
recall = tp / max(p, small) ;
if isempty(opts.normalizePrior)
precision = max(tp, small) ./ max(tp + fp, small) ;
else
a = opts.normalizePrior ;
precision = max(tp * a/max(p,small), small) ./ ...
max(tp * a/max(p,small) + fp * (1-a)/max(n,small), small) ;
end
% interpolate precision if needed
if opts.interpolate
precision = fliplr(vl_cummax(fliplr(precision))) ;
end
% --------------------------------------------------------------------
% Additional info
% --------------------------------------------------------------------
if nargout > 2 || nargout == 0
% area under the curve using trapezoid interpolation
if ~opts.interpolate
info.auc = 0.5 * sum((precision(1:end-1) + precision(2:end)) .* diff(recall)) ;
end
% average precision (for each recalled positive sample)
sel = find(diff(recall)) + 1 ;
info.ap = sum(precision(sel)) / p ;
if opts.interpolate
info.auc = info.ap ;
end
% TREC 11 points average interpolated precision
info.ap_interp_11 = 0.0 ;
for rc = linspace(0,1,11)
pr = max([0, precision(recall >= rc)]) ;
info.ap_interp_11 = info.ap_interp_11 + pr / 11 ;
end
% legacy definition
info.auc_pa08 = info.ap_interp_11 ;
end
% --------------------------------------------------------------------
% Plot
% --------------------------------------------------------------------
if nargout == 0
cla ; hold on ;
plot(recall,precision,'linewidth',2) ;
if isempty(opts.normalizePrior)
randomPrecision = p / (p + n) ;
else
randomPrecision = opts.normalizePrior ;
end
spline([0 1], [1 1] * randomPrecision, 'r--', 'linewidth', 2) ;
axis square ; grid on ;
xlim([0 1]) ; xlabel('recall') ;
ylim([0 1]) ; ylabel('precision') ;
title(sprintf('PR (AUC: %.2f%%, AP: %.2f%%, AP11: %.2f%%)', ...
info.auc * 100, ...
info.ap * 100, ...
info.ap_interp_11 * 100)) ;
if opts.interpolate
legend('PR interp.', 'PR rand.', 'Location', 'SouthEast') ;
else
legend('PR', 'PR rand.', 'Location', 'SouthEast') ;
end
clear recall precision info ;
end
% --------------------------------------------------------------------
% Stable output
% --------------------------------------------------------------------
if opts.stable
precision(1) = [] ;
recall(1) = [] ;
precision_ = precision ;
recall_ = recall ;
precision = NaN(size(precision)) ;
recall = NaN(size(recall)) ;
precision(perm) = precision_ ;
recall(perm) = recall_ ;
end
% --------------------------------------------------------------------
function h = spline(x,y,spec,varargin)
% --------------------------------------------------------------------
prop = vl_linespec2prop(spec) ;
h = line(x,y,prop{:},varargin{:}) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_ubcread.m
|
.m
|
ObjectDetection-master/Project-GUI/vlfeat-0.9.20/toolbox/sift/vl_ubcread.m
| 3,015 |
utf_8
|
e8ddd3ecd87e76b6c738ba153fef050f
|
function [f,d] = vl_ubcread(file, varargin)
% SIFTREAD Read Lowe's SIFT implementation data files
% [F,D] = VL_UBCREAD(FILE) reads the frames F and the descriptors D
% from FILE in UBC (Lowe's original implementation of SIFT) format
% and returns F and D as defined by VL_SIFT().
%
% VL_UBCREAD(FILE, 'FORMAT', 'OXFORD') assumes the format used by
% Oxford VGG implementations .
%
% See also: VL_SIFT(), VL_HELP().
% Authors: Andrea Vedaldi
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.verbosity = 0 ;
opts.format = 'ubc' ;
opts = vl_argparse(opts, varargin) ;
g = fopen(file, 'r');
if g == -1
error(['Could not open file ''', file, '''.']) ;
end
[header, count] = fscanf(g, '%d', [1 2]) ;
if count ~= 2
error('Invalid keypoint file header.');
end
switch opts.format
case 'ubc'
numKeypoints = header(1) ;
descrLen = header(2) ;
case 'oxford'
numKeypoints = header(2) ;
descrLen = header(1) ;
otherwise
error('Unknown format ''%s''.', opts.format) ;
end
if(opts.verbosity > 0)
fprintf('%d keypoints, %d descriptor length.\n', numKeypoints, descrLen) ;
end
%creates two output matrices
switch opts.format
case 'ubc'
P = zeros(4,numKeypoints) ;
case 'oxford'
P = zeros(5,numKeypoints) ;
end
L = zeros(descrLen, numKeypoints) ;
%parse tmp.key
for k = 1:numKeypoints
switch opts.format
case 'ubc'
% Record format: i,j,s,th
[record, count] = fscanf(g, '%f', [1 4]) ;
if count ~= 4
error(...
sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) );
end
P(:,k) = record(:) ;
case 'oxford'
% Record format: x, y, a, b, c such that x' [a b ; b c] x = 1
[record, count] = fscanf(g, '%f', [1 5]) ;
if count ~= 5
error(...
sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) );
end
P(:,k) = record(:) ;
end
% Record format: descriptor
[record, count] = fscanf(g, '%d', [1 descrLen]) ;
if count ~= descrLen
error(...
sprintf('Invalid keypoint file (parsing keypoint %d, descriptor part)',k) );
end
L(:,k) = record(:) ;
end
fclose(g) ;
switch opts.format
case 'ubc'
P(1:2,:) = flipud(P(1:2,:)) + 1 ; % i,j -> x,y
f=[ P(1:2,:) ; P(3,:) ; -P(4,:) ] ;
d=uint8(L) ;
p=[1 2 3 4 5 6 7 8] ;
q=[1 8 7 6 5 4 3 2] ;
for j=0:3
for i=0:3
d(8*(i+4*j)+p,:) = d(8*(i+4*j)+q,:) ;
end
end
case 'oxford'
P(1:2,:) = P(1:2,:) + 1 ; % matlab origin
f = P ;
f(3:5,:) = inv2x2(f(3:5,:)) ;
d = uint8(L) ;
end
% --------------------------------------------------------------------
function S = inv2x2(C)
% --------------------------------------------------------------------
den = C(1,:) .* C(3,:) - C(2,:) .* C(2,:) ;
S = [C(3,:) ; -C(2,:) ; C(1,:)] ./ den([1 1 1], :) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_frame2oell.m
|
.m
|
ObjectDetection-master/Project-GUI/vlfeat-0.9.20/toolbox/sift/vl_frame2oell.m
| 2,806 |
utf_8
|
c93792632f630743485fa4c2cf12d647
|
function eframes = vl_frame2oell(frames)
% VL_FRAMES2OELL Convert a geometric frame to an oriented ellipse
% EFRAME = VL_FRAME2OELL(FRAME) converts the generic FRAME to an
% oriented ellipses EFRAME. FRAME and EFRAME can be matrices, with
% one frame per column.
%
% A frame is either a point, a disc, an oriented disc, an ellipse,
% or an oriented ellipse. These are represented respectively by 2,
% 3, 4, 5 and 6 parameters each, as described in VL_PLOTFRAME(). An
% oriented ellipse is the most general geometric frame; hence, there
% is no loss of information in this conversion.
%
% If FRAME is an oriented disc or ellipse, then the conversion is
% immediate. If, however, FRAME is not oriented (it is either a
% point or an unoriented disc or ellipse), then an orientation must
% be assigned. The orientation is chosen in such a way that the
% affine transformation that maps the standard oriented frame into
% the output EFRAME does not rotate the Y axis. If frames represent
% detected visual features, this convention corresponds to assume
% that features are upright.
%
% If FRAME is a point, then the output is an ellipse with null area.
%
% See: <a href="matlab:vl_help('tut.frame')">feature frames</a>,
% VL_PLOTFRAME(), VL_HELP().
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
[D,K] = size(frames) ;
eframes = zeros(6,K) ;
switch D
case 2
eframes(1:2,:) = frames(1:2,:) ;
case 3
eframes(1:2,:) = frames(1:2,:) ;
eframes(3,:) = frames(3,:) ;
eframes(6,:) = frames(3,:) ;
case 4
r = frames(3,:) ;
c = r.*cos(frames(4,:)) ;
s = r.*sin(frames(4,:)) ;
eframes(1:2,:) = frames(1:2,:) ;
eframes(3:6,:) = [c ; s ; -s ; c] ;
case 5
eframes(1:2,:) = frames(1:2,:) ;
eframes(3:6,:) = mapFromS(frames(3:5,:)) ;
case 6
eframes = frames ;
otherwise
error('FRAMES format is unknown.') ;
end
% --------------------------------------------------------------------
function A = mapFromS(S)
% --------------------------------------------------------------------
% Returns the (stacking of the) 2x2 matrix A that maps the unit circle
% into the ellipses satisfying the equation x' inv(S) x = 1. Here S
% is a stacked covariance matrix, with elements S11, S12 and S22.
%
% The goal is to find A such that AA' = S. In order to let the Y
% direction unaffected (upright feature), the assumption is taht
% A = [a b ; 0 c]. Hence
%
% AA' = [a^2, ab ; ab, b^2+c^2] = S.
A = zeros(4,size(S,2)) ;
a = sqrt(S(1,:));
b = S(2,:) ./ max(a, 1e-18) ;
A(1,:) = a ;
A(2,:) = b ;
A(4,:) = sqrt(max(S(3,:) - b.*b, 0)) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_plotsiftdescriptor.m
|
.m
|
ObjectDetection-master/Project-GUI/vlfeat-0.9.20/toolbox/sift/vl_plotsiftdescriptor.m
| 5,114 |
utf_8
|
a4e125a8916653f00143b61cceda2f23
|
function h=vl_plotsiftdescriptor(d,f,varargin)
% VL_PLOTSIFTDESCRIPTOR Plot SIFT descriptor
% VL_PLOTSIFTDESCRIPTOR(D) plots the SIFT descriptor D. If D is a
% matrix, it plots one descriptor per column. D has the same format
% used by VL_SIFT().
%
% VL_PLOTSIFTDESCRIPTOR(D,F) plots the SIFT descriptors warped to
% the SIFT frames F, specified as columns of the matrix F. F has the
% same format used by VL_SIFT().
%
% H=VL_PLOTSIFTDESCRIPTOR(...) returns the handle H to the line
% drawing representing the descriptors.
%
% The function assumes that the SIFT descriptors use the standard
% configuration of 4x4 spatial bins and 8 orientations bins. The
% following parameters can be used to change this:
%
% NumSpatialBins:: 4
% Number of spatial bins in both spatial directions X and Y.
%
% NumOrientationBins:: 8
% Number of orientation bis.
%
% MagnificationFactor:: 3
% Magnification factor. The width of one bin is equal to the scale
% of the keypoint F multiplied by this factor.
%
% See also: VL_SIFT(), VL_PLOTFRAME(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.magnificationFactor = 3.0 ;
opts.numSpatialBins = 4 ;
opts.numOrientationBins = 8 ;
opts.maxValue = 0 ;
if nargin > 1
if ~ isnumeric(f)
error('F must be a numeric type (use [] to leave it unspecified)') ;
end
end
opts = vl_argparse(opts, varargin) ;
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
if(size(d,1) ~= opts.numSpatialBins^2 * opts.numOrientationBins)
error('The number of rows of D does not match the geometry of the descriptor') ;
end
if nargin > 1
if (~isempty(f) & (size(f,1) < 2 | size(f,1) > 6))
error('F must be either empty of have from 2 to six rows.');
end
if size(f,1) == 2
% translation only
f(3:6,:) = deal([10 0 0 10]') ;
%f = [f; 10 * ones(1, size(f,2)) ; 0 * zeros(1, size(f,2))] ;
end
if size(f,1) == 3
% translation and scale
f(3:6,:) = [1 0 0 1]' * f(3,:) ;
%f = [f; 0 * zeros(1, size(f,2))] ;
end
if size(f,1) == 4
c = cos(f(4,:)) ;
s = sin(f(4,:)) ;
f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ;
end
if size(f,1) == 5
assert(false) ;
c = cos(f(4,:)) ;
s = sin(f(4,:)) ;
f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ;
end
if(~isempty(f) & size(f,2) ~= size(d,2))
error('D and F have incompatible dimension') ;
end
end
% Descriptors are often non-double numeric arrays
d = double(d) ;
K = size(d,2) ;
if nargin < 2 | isempty(f)
f = repmat([0;0;1;0;0;1],1,K) ;
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
xall=[] ;
yall=[] ;
for k=1:K
[x,y] = render_descr(d(:,k), opts.numSpatialBins, opts.numOrientationBins, opts.maxValue) ;
xall = [xall opts.magnificationFactor*f(3,k)*x + opts.magnificationFactor*f(5,k)*y + f(1,k)] ;
yall = [yall opts.magnificationFactor*f(4,k)*x + opts.magnificationFactor*f(6,k)*y + f(2,k)] ;
end
h=line(xall,yall) ;
% --------------------------------------------------------------------
function [x,y] = render_descr(d, numSpatialBins, numOrientationBins, maxValue)
% --------------------------------------------------------------------
% Get the coordinates of the lines of the SIFT grid; each bin has side 1
[x,y] = meshgrid(-numSpatialBins/2:numSpatialBins/2,-numSpatialBins/2:numSpatialBins/2) ;
% Get the corresponding bin centers
xc = x(1:end-1,1:end-1) + 0.5 ;
yc = y(1:end-1,1:end-1) + 0.5 ;
% Rescale the descriptor range so that the biggest peak fits inside the bin diagram
if maxValue
d = 0.4 * d / maxValue ;
else
d = 0.4 * d / max(d(:)+eps) ;
end
% We scramble the the centers to have them in row major order
% (descriptor convention).
xc = xc' ;
yc = yc' ;
% Each spatial bin contains a star with numOrientationBins tips
xc = repmat(xc(:)',numOrientationBins,1) ;
yc = repmat(yc(:)',numOrientationBins,1) ;
% Do the stars
th=linspace(0,2*pi,numOrientationBins+1) ;
th=th(1:end-1) ;
xd = repmat(cos(th), 1, numSpatialBins*numSpatialBins) ;
yd = repmat(sin(th), 1, numSpatialBins*numSpatialBins) ;
xd = xd .* d(:)' ;
yd = yd .* d(:)' ;
% Re-arrange in sequential order the lines to draw
nans = NaN * ones(1,numSpatialBins^2*numOrientationBins) ;
x1 = xc(:)' ;
y1 = yc(:)' ;
x2 = x1 + xd ;
y2 = y1 + yd ;
xstars = [x1;x2;nans] ;
ystars = [y1;y2;nans] ;
% Horizontal lines of the grid
nans = NaN * ones(1,numSpatialBins+1);
xh = [x(:,1)' ; x(:,end)' ; nans] ;
yh = [y(:,1)' ; y(:,end)' ; nans] ;
% Verical lines of the grid
xv = [x(1,:) ; x(end,:) ; nans] ;
yv = [y(1,:) ; y(end,:) ; nans] ;
x=[xstars(:)' xh(:)' xv(:)'] ;
y=[ystars(:)' yh(:)' yv(:)'] ;
|
github
|
sabbiu/ObjectDetection-master
|
phow_caltech101.m
|
.m
|
ObjectDetection-master/Project-GUI/vlfeat-0.9.20/apps/phow_caltech101.m
| 11,594 |
utf_8
|
7f4890a2e6844ca56debbfe23cca64f3
|
function phow_caltech101()
% PHOW_CALTECH101 Image classification in the Caltech-101 dataset
% This program demonstrates how to use VLFeat to construct an image
% classifier on the Caltech-101 data. The classifier uses PHOW
% features (dense SIFT), spatial histograms of visual words, and a
% Chi2 SVM. To speedup computation it uses VLFeat fast dense SIFT,
% kd-trees, and homogeneous kernel map. The program also
% demonstrates VLFeat PEGASOS SVM solver, although for this small
% dataset other solvers such as LIBLINEAR can be more efficient.
%
% By default 15 training images are used, which should result in
% about 64% performance (a good performance considering that only a
% single feature type is being used).
%
% Call PHOW_CALTECH101 to train and test a classifier on a small
% subset of the Caltech-101 data. Note that the program
% automatically downloads a copy of the Caltech-101 data from the
% Internet if it cannot find a local copy.
%
% Edit the PHOW_CALTECH101 file to change the program configuration.
%
% To run on the entire dataset change CONF.TINYPROBLEM to FALSE.
%
% The Caltech-101 data is saved into CONF.CALDIR, which defaults to
% 'data/caltech-101'. Change this path to the desired location, for
% instance to point to an existing copy of the Caltech-101 data.
%
% The program can also be used to train a model on custom data by
% pointing CONF.CALDIR to it. Just create a subdirectory for each
% class and put the training images there. Make sure to adjust
% CONF.NUMTRAIN accordingly.
%
% Intermediate files are stored in the directory CONF.DATADIR. All
% such files begin with the prefix CONF.PREFIX, which can be changed
% to test different parameter settings without overriding previous
% results.
%
% The program saves the trained model in
% <CONF.DATADIR>/<CONF.PREFIX>-model.mat. This model can be used to
% test novel images independently of the Caltech data.
%
% load('data/baseline-model.mat') ; # change to the model path
% label = model.classify(model, im) ;
%
% Author: Andrea Vedaldi
% Copyright (C) 2011-2013 Andrea Vedaldi
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
conf.calDir = 'data/caltech-101' ;
conf.dataDir = 'data/' ;
conf.autoDownloadData = true ;
conf.numTrain = 15 ;
conf.numTest = 15 ;
conf.numClasses = 102 ;
conf.numWords = 600 ;
conf.numSpatialX = [2 4] ;
conf.numSpatialY = [2 4] ;
conf.quantizer = 'kdtree' ;
conf.svm.C = 10 ;
conf.svm.solver = 'sdca' ;
%conf.svm.solver = 'sgd' ;
%conf.svm.solver = 'liblinear' ;
conf.svm.biasMultiplier = 1 ;
conf.phowOpts = {'Step', 3} ;
conf.clobber = false ;
conf.tinyProblem = true ;
conf.prefix = 'baseline' ;
conf.randSeed = 1 ;
if conf.tinyProblem
conf.prefix = 'tiny' ;
conf.numClasses = 5 ;
conf.numSpatialX = 2 ;
conf.numSpatialY = 2 ;
conf.numWords = 300 ;
conf.phowOpts = {'Verbose', 2, 'Sizes', 7, 'Step', 5} ;
end
conf.vocabPath = fullfile(conf.dataDir, [conf.prefix '-vocab.mat']) ;
conf.histPath = fullfile(conf.dataDir, [conf.prefix '-hists.mat']) ;
conf.modelPath = fullfile(conf.dataDir, [conf.prefix '-model.mat']) ;
conf.resultPath = fullfile(conf.dataDir, [conf.prefix '-result']) ;
randn('state',conf.randSeed) ;
rand('state',conf.randSeed) ;
vl_twister('state',conf.randSeed) ;
% --------------------------------------------------------------------
% Download Caltech-101 data
% --------------------------------------------------------------------
if ~exist(conf.calDir, 'dir') || ...
(~exist(fullfile(conf.calDir, 'airplanes'),'dir') && ...
~exist(fullfile(conf.calDir, '101_ObjectCategories', 'airplanes')))
if ~conf.autoDownloadData
error(...
['Caltech-101 data not found. ' ...
'Set conf.autoDownloadData=true to download the required data.']) ;
end
vl_xmkdir(conf.calDir) ;
calUrl = ['http://www.vision.caltech.edu/Image_Datasets/' ...
'Caltech101/101_ObjectCategories.tar.gz'] ;
fprintf('Downloading Caltech-101 data to ''%s''. This will take a while.', conf.calDir) ;
untar(calUrl, conf.calDir) ;
end
if ~exist(fullfile(conf.calDir, 'airplanes'),'dir')
conf.calDir = fullfile(conf.calDir, '101_ObjectCategories') ;
end
% --------------------------------------------------------------------
% Setup data
% --------------------------------------------------------------------
classes = dir(conf.calDir) ;
classes = classes([classes.isdir]) ;
classes = {classes(3:conf.numClasses+2).name} ;
images = {} ;
imageClass = {} ;
for ci = 1:length(classes)
ims = dir(fullfile(conf.calDir, classes{ci}, '*.jpg'))' ;
ims = vl_colsubset(ims, conf.numTrain + conf.numTest) ;
ims = cellfun(@(x)fullfile(classes{ci},x),{ims.name},'UniformOutput',false) ;
images = {images{:}, ims{:}} ;
imageClass{end+1} = ci * ones(1,length(ims)) ;
end
selTrain = find(mod(0:length(images)-1, conf.numTrain+conf.numTest) < conf.numTrain) ;
selTest = setdiff(1:length(images), selTrain) ;
imageClass = cat(2, imageClass{:}) ;
model.classes = classes ;
model.phowOpts = conf.phowOpts ;
model.numSpatialX = conf.numSpatialX ;
model.numSpatialY = conf.numSpatialY ;
model.quantizer = conf.quantizer ;
model.vocab = [] ;
model.w = [] ;
model.b = [] ;
model.classify = @classify ;
% --------------------------------------------------------------------
% Train vocabulary
% --------------------------------------------------------------------
if ~exist(conf.vocabPath) || conf.clobber
% Get some PHOW descriptors to train the dictionary
selTrainFeats = vl_colsubset(selTrain, 30) ;
descrs = {} ;
%for ii = 1:length(selTrainFeats)
parfor ii = 1:length(selTrainFeats)
im = imread(fullfile(conf.calDir, images{selTrainFeats(ii)})) ;
im = standarizeImage(im) ;
[drop, descrs{ii}] = vl_phow(im, model.phowOpts{:}) ;
end
descrs = vl_colsubset(cat(2, descrs{:}), 10e4) ;
descrs = single(descrs) ;
% Quantize the descriptors to get the visual words
vocab = vl_kmeans(descrs, conf.numWords, 'verbose', 'algorithm', 'elkan', 'MaxNumIterations', 50) ;
save(conf.vocabPath, 'vocab') ;
else
load(conf.vocabPath) ;
end
model.vocab = vocab ;
if strcmp(model.quantizer, 'kdtree')
model.kdtree = vl_kdtreebuild(vocab) ;
end
% --------------------------------------------------------------------
% Compute spatial histograms
% --------------------------------------------------------------------
if ~exist(conf.histPath) || conf.clobber
hists = {} ;
parfor ii = 1:length(images)
% for ii = 1:length(images)
fprintf('Processing %s (%.2f %%)\n', images{ii}, 100 * ii / length(images)) ;
im = imread(fullfile(conf.calDir, images{ii})) ;
hists{ii} = getImageDescriptor(model, im);
end
hists = cat(2, hists{:}) ;
save(conf.histPath, 'hists') ;
else
load(conf.histPath) ;
end
% --------------------------------------------------------------------
% Compute feature map
% --------------------------------------------------------------------
psix = vl_homkermap(hists, 1, 'kchi2', 'gamma', .5) ;
% --------------------------------------------------------------------
% Train SVM
% --------------------------------------------------------------------
if ~exist(conf.modelPath) || conf.clobber
switch conf.svm.solver
case {'sgd', 'sdca'}
lambda = 1 / (conf.svm.C * length(selTrain)) ;
w = [] ;
parfor ci = 1:length(classes)
perm = randperm(length(selTrain)) ;
fprintf('Training model for class %s\n', classes{ci}) ;
y = 2 * (imageClass(selTrain) == ci) - 1 ;
[w(:,ci) b(ci) info] = vl_svmtrain(psix(:, selTrain(perm)), y(perm), lambda, ...
'Solver', conf.svm.solver, ...
'MaxNumIterations', 50/lambda, ...
'BiasMultiplier', conf.svm.biasMultiplier, ...
'Epsilon', 1e-3);
end
case 'liblinear'
svm = train(imageClass(selTrain)', ...
sparse(double(psix(:,selTrain))), ...
sprintf(' -s 3 -B %f -c %f', ...
conf.svm.biasMultiplier, conf.svm.C), ...
'col') ;
w = svm.w(:,1:end-1)' ;
b = svm.w(:,end)' ;
end
model.b = conf.svm.biasMultiplier * b ;
model.w = w ;
save(conf.modelPath, 'model') ;
else
load(conf.modelPath) ;
end
% --------------------------------------------------------------------
% Test SVM and evaluate
% --------------------------------------------------------------------
% Estimate the class of the test images
scores = model.w' * psix + model.b' * ones(1,size(psix,2)) ;
[drop, imageEstClass] = max(scores, [], 1) ;
% Compute the confusion matrix
idx = sub2ind([length(classes), length(classes)], ...
imageClass(selTest), imageEstClass(selTest)) ;
confus = zeros(length(classes)) ;
confus = vl_binsum(confus, ones(size(idx)), idx) ;
% Plots
figure(1) ; clf;
subplot(1,2,1) ;
imagesc(scores(:,[selTrain selTest])) ; title('Scores') ;
set(gca, 'ytick', 1:length(classes), 'yticklabel', classes) ;
subplot(1,2,2) ;
imagesc(confus) ;
title(sprintf('Confusion matrix (%.2f %% accuracy)', ...
100 * mean(diag(confus)/conf.numTest) )) ;
print('-depsc2', [conf.resultPath '.ps']) ;
save([conf.resultPath '.mat'], 'confus', 'conf') ;
% -------------------------------------------------------------------------
function im = standarizeImage(im)
% -------------------------------------------------------------------------
im = im2single(im) ;
if size(im,1) > 480, im = imresize(im, [480 NaN]) ; end
% -------------------------------------------------------------------------
function hist = getImageDescriptor(model, im)
% -------------------------------------------------------------------------
im = standarizeImage(im) ;
width = size(im,2) ;
height = size(im,1) ;
numWords = size(model.vocab, 2) ;
% get PHOW features
[frames, descrs] = vl_phow(im, model.phowOpts{:}) ;
% quantize local descriptors into visual words
switch model.quantizer
case 'vq'
[drop, binsa] = min(vl_alldist(model.vocab, single(descrs)), [], 1) ;
case 'kdtree'
binsa = double(vl_kdtreequery(model.kdtree, model.vocab, ...
single(descrs), ...
'MaxComparisons', 50)) ;
end
for i = 1:length(model.numSpatialX)
binsx = vl_binsearch(linspace(1,width,model.numSpatialX(i)+1), frames(1,:)) ;
binsy = vl_binsearch(linspace(1,height,model.numSpatialY(i)+1), frames(2,:)) ;
% combined quantization
bins = sub2ind([model.numSpatialY(i), model.numSpatialX(i), numWords], ...
binsy,binsx,binsa) ;
hist = zeros(model.numSpatialY(i) * model.numSpatialX(i) * numWords, 1) ;
hist = vl_binsum(hist, ones(size(bins)), bins) ;
hists{i} = single(hist / sum(hist)) ;
end
hist = cat(1,hists{:}) ;
hist = hist / sum(hist) ;
% -------------------------------------------------------------------------
function [className, score] = classify(model, im)
% -------------------------------------------------------------------------
hist = getImageDescriptor(model, im) ;
psix = vl_homkermap(hist, 1, 'kchi2', 'gamma', .5) ;
scores = model.w' * psix + model.b' ;
[score, best] = max(scores) ;
className = model.classes{best} ;
|
github
|
sabbiu/ObjectDetection-master
|
sift_mosaic.m
|
.m
|
ObjectDetection-master/Project-GUI/vlfeat-0.9.20/apps/sift_mosaic.m
| 4,621 |
utf_8
|
8fa3ad91b401b8f2400fb65944c79712
|
function mosaic = sift_mosaic(im1, im2)
% SIFT_MOSAIC Demonstrates matching two images using SIFT and RANSAC
%
% SIFT_MOSAIC demonstrates matching two images based on SIFT
% features and RANSAC and computing their mosaic.
%
% SIFT_MOSAIC by itself runs the algorithm on two standard test
% images. Use SIFT_MOSAIC(IM1,IM2) to compute the mosaic of two
% custom images IM1 and IM2.
% AUTORIGHTS
if nargin == 0
im1 = imread(fullfile(vl_root, 'data', 'river1.jpg')) ;
im2 = imread(fullfile(vl_root, 'data', 'river2.jpg')) ;
end
% make single
im1 = im2single(im1) ;
im2 = im2single(im2) ;
% make grayscale
if size(im1,3) > 1, im1g = rgb2gray(im1) ; else im1g = im1 ; end
if size(im2,3) > 1, im2g = rgb2gray(im2) ; else im2g = im2 ; end
% --------------------------------------------------------------------
% SIFT matches
% --------------------------------------------------------------------
[f1,d1] = vl_sift(im1g) ;
[f2,d2] = vl_sift(im2g) ;
[matches, scores] = vl_ubcmatch(d1,d2) ;
numMatches = size(matches,2) ;
X1 = f1(1:2,matches(1,:)) ; X1(3,:) = 1 ;
X2 = f2(1:2,matches(2,:)) ; X2(3,:) = 1 ;
% --------------------------------------------------------------------
% RANSAC with homography model
% --------------------------------------------------------------------
clear H score ok ;
for t = 1:100
% estimate homograpyh
subset = vl_colsubset(1:numMatches, 4) ;
A = [] ;
for i = subset
A = cat(1, A, kron(X1(:,i)', vl_hat(X2(:,i)))) ;
end
[U,S,V] = svd(A) ;
H{t} = reshape(V(:,9),3,3) ;
% score homography
X2_ = H{t} * X1 ;
du = X2_(1,:)./X2_(3,:) - X2(1,:)./X2(3,:) ;
dv = X2_(2,:)./X2_(3,:) - X2(2,:)./X2(3,:) ;
ok{t} = (du.*du + dv.*dv) < 6*6 ;
score(t) = sum(ok{t}) ;
end
[score, best] = max(score) ;
H = H{best} ;
ok = ok{best} ;
% --------------------------------------------------------------------
% Optional refinement
% --------------------------------------------------------------------
function err = residual(H)
u = H(1) * X1(1,ok) + H(4) * X1(2,ok) + H(7) ;
v = H(2) * X1(1,ok) + H(5) * X1(2,ok) + H(8) ;
d = H(3) * X1(1,ok) + H(6) * X1(2,ok) + 1 ;
du = X2(1,ok) - u ./ d ;
dv = X2(2,ok) - v ./ d ;
err = sum(du.*du + dv.*dv) ;
end
if exist('fminsearch') == 2
H = H / H(3,3) ;
opts = optimset('Display', 'none', 'TolFun', 1e-8, 'TolX', 1e-8) ;
H(1:8) = fminsearch(@residual, H(1:8)', opts) ;
else
warning('Refinement disabled as fminsearch was not found.') ;
end
% --------------------------------------------------------------------
% Show matches
% --------------------------------------------------------------------
dh1 = max(size(im2,1)-size(im1,1),0) ;
dh2 = max(size(im1,1)-size(im2,1),0) ;
figure(1) ; clf ;
subplot(2,1,1) ;
imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ;
o = size(im1,2) ;
line([f1(1,matches(1,:));f2(1,matches(2,:))+o], ...
[f1(2,matches(1,:));f2(2,matches(2,:))]) ;
title(sprintf('%d tentative matches', numMatches)) ;
axis image off ;
subplot(2,1,2) ;
imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ;
o = size(im1,2) ;
line([f1(1,matches(1,ok));f2(1,matches(2,ok))+o], ...
[f1(2,matches(1,ok));f2(2,matches(2,ok))]) ;
title(sprintf('%d (%.2f%%) inliner matches out of %d', ...
sum(ok), ...
100*sum(ok)/numMatches, ...
numMatches)) ;
axis image off ;
drawnow ;
% --------------------------------------------------------------------
% Mosaic
% --------------------------------------------------------------------
box2 = [1 size(im2,2) size(im2,2) 1 ;
1 1 size(im2,1) size(im2,1) ;
1 1 1 1 ] ;
box2_ = inv(H) * box2 ;
box2_(1,:) = box2_(1,:) ./ box2_(3,:) ;
box2_(2,:) = box2_(2,:) ./ box2_(3,:) ;
ur = min([1 box2_(1,:)]):max([size(im1,2) box2_(1,:)]) ;
vr = min([1 box2_(2,:)]):max([size(im1,1) box2_(2,:)]) ;
[u,v] = meshgrid(ur,vr) ;
im1_ = vl_imwbackward(im2double(im1),u,v) ;
z_ = H(3,1) * u + H(3,2) * v + H(3,3) ;
u_ = (H(1,1) * u + H(1,2) * v + H(1,3)) ./ z_ ;
v_ = (H(2,1) * u + H(2,2) * v + H(2,3)) ./ z_ ;
im2_ = vl_imwbackward(im2double(im2),u_,v_) ;
mass = ~isnan(im1_) + ~isnan(im2_) ;
im1_(isnan(im1_)) = 0 ;
im2_(isnan(im2_)) = 0 ;
mosaic = (im1_ + im2_) ./ mass ;
figure(2) ; clf ;
imagesc(mosaic) ; axis image off ;
title('Mosaic') ;
if nargout == 0, clear mosaic ; end
end
|
github
|
sabbiu/ObjectDetection-master
|
encodeImage.m
|
.m
|
ObjectDetection-master/Project-GUI/vlfeat-0.9.20/apps/recognition/encodeImage.m
| 5,278 |
utf_8
|
5d9dc6161995b8e10366b5649bf4fda4
|
function descrs = encodeImage(encoder, im, varargin)
% ENCODEIMAGE Apply an encoder to an image
% DESCRS = ENCODEIMAGE(ENCODER, IM) applies the ENCODER
% to image IM, returning a corresponding code vector PSI.
%
% IM can be an image, the path to an image, or a cell array of
% the same, to operate on multiple images.
%
% ENCODEIMAGE(ENCODER, IM, CACHE) utilizes the specified CACHE
% directory to store encodings for the given images. The cache
% is used only if the images are specified as file names.
%
% See also: TRAINENCODER().
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.cacheDir = [] ;
opts.cacheChunkSize = 512 ;
opts = vl_argparse(opts,varargin) ;
if ~iscell(im), im = {im} ; end
% break the computation into cached chunks
startTime = tic ;
descrs = cell(1, numel(im)) ;
numChunks = ceil(numel(im) / opts.cacheChunkSize) ;
for c = 1:numChunks
n = min(opts.cacheChunkSize, numel(im) - (c-1)*opts.cacheChunkSize) ;
chunkPath = fullfile(opts.cacheDir, sprintf('chunk-%03d.mat',c)) ;
if ~isempty(opts.cacheDir) && exist(chunkPath)
fprintf('%s: loading descriptors from %s\n', mfilename, chunkPath) ;
load(chunkPath, 'data') ;
else
range = (c-1)*opts.cacheChunkSize + (1:n) ;
fprintf('%s: processing a chunk of %d images (%3d of %3d, %5.1fs to go)\n', ...
mfilename, numel(range), ...
c, numChunks, toc(startTime) / (c - 1) * (numChunks - c + 1)) ;
data = processChunk(encoder, im(range)) ;
if ~isempty(opts.cacheDir)
save(chunkPath, 'data') ;
end
end
descrs{c} = data ;
clear data ;
end
descrs = cat(2,descrs{:}) ;
% --------------------------------------------------------------------
function psi = processChunk(encoder, im)
% --------------------------------------------------------------------
psi = cell(1,numel(im)) ;
if numel(im) > 1 & matlabpool('size') > 1
parfor i = 1:numel(im)
psi{i} = encodeOne(encoder, im{i}) ;
end
else
% avoiding parfor makes debugging easier
for i = 1:numel(im)
psi{i} = encodeOne(encoder, im{i}) ;
end
end
psi = cat(2, psi{:}) ;
% --------------------------------------------------------------------
function psi = encodeOne(encoder, im)
% --------------------------------------------------------------------
im = encoder.readImageFn(im) ;
features = encoder.extractorFn(im) ;
imageSize = size(im) ;
psi = {} ;
for i = 1:size(encoder.subdivisions,2)
minx = encoder.subdivisions(1,i) * imageSize(2) ;
miny = encoder.subdivisions(2,i) * imageSize(1) ;
maxx = encoder.subdivisions(3,i) * imageSize(2) ;
maxy = encoder.subdivisions(4,i) * imageSize(1) ;
ok = ...
minx <= features.frame(1,:) & features.frame(1,:) < maxx & ...
miny <= features.frame(2,:) & features.frame(2,:) < maxy ;
descrs = encoder.projection * bsxfun(@minus, ...
features.descr(:,ok), ...
encoder.projectionCenter) ;
if encoder.renormalize
descrs = bsxfun(@times, descrs, 1./max(1e-12, sqrt(sum(descrs.^2)))) ;
end
w = size(im,2) ;
h = size(im,1) ;
frames = features.frame(1:2,:) ;
frames = bsxfun(@times, bsxfun(@minus, frames, [w;h]/2), 1./[w;h]) ;
descrs = extendDescriptorsWithGeometry(encoder.geometricExtension, frames, descrs) ;
switch encoder.type
case 'bovw'
[words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ...
descrs, ...
'MaxComparisons', 100) ;
z = vl_binsum(zeros(encoder.numWords,1), 1, double(words)) ;
z = sqrt(z) ;
case 'fv'
z = vl_fisher(descrs, ...
encoder.means, ...
encoder.covariances, ...
encoder.priors, ...
'Improved') ;
case 'vlad'
[words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ...
descrs, ...
'MaxComparisons', 15) ;
assign = zeros(encoder.numWords, numel(words), 'single') ;
assign(sub2ind(size(assign), double(words), 1:numel(words))) = 1 ;
z = vl_vlad(descrs, ...
encoder.words, ...
assign, ...
'SquareRoot', ...
'NormalizeComponents') ;
end
z = z / max(sqrt(sum(z.^2)), 1e-12) ;
psi{i} = z(:) ;
end
psi = cat(1, psi{:}) ;
% --------------------------------------------------------------------
function psi = getFromCache(name, cache)
% --------------------------------------------------------------------
[drop, name] = fileparts(name) ;
cachePath = fullfile(cache, [name '.mat']) ;
if exist(cachePath, 'file')
data = load(cachePath) ;
psi = data.psi ;
else
psi = [] ;
end
% --------------------------------------------------------------------
function storeToCache(name, cache, psi)
% --------------------------------------------------------------------
[drop, name] = fileparts(name) ;
cachePath = fullfile(cache, [name '.mat']) ;
vl_xmkdir(cache) ;
data.psi = psi ;
save(cachePath, '-STRUCT', 'data') ;
|
github
|
sabbiu/ObjectDetection-master
|
experiments.m
|
.m
|
ObjectDetection-master/Project-GUI/vlfeat-0.9.20/apps/recognition/experiments.m
| 6,905 |
utf_8
|
1e4a4911eed4a451b9488b9e6cc9b39c
|
function experiments()
% EXPERIMENTS Run image classification experiments
% The experimens download a number of benchmark datasets in the
% 'data/' subfolder. Make sure that there are several GBs of
% space available.
%
% By default, experiments run with a lite option turned on. This
% quickly runs all of them on tiny subsets of the actual data.
% This is used only for testing; to run the actual experiments,
% set the lite variable to false.
%
% Running all the experiments is a slow process. Using parallel
% MATLAB and several cores/machiens is suggested.
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
lite = true ;
clear ex ;
ex(1).prefix = 'fv-aug' ;
ex(1).trainOpts = {'C', 10} ;
ex(1).datasets = {'fmd', 'scene67'} ;
ex(1).seed = 1 ;
ex(1).opts = {...
'type', 'fv', ...
'numWords', 256, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'xy', ...
'numPcaDimensions', 80, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(2) = ex(1) ;
ex(2).datasets = {'caltech101'} ;
ex(2).opts{end} = @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(0:-.5:-3)) ;
ex(3) = ex(1) ;
ex(3).datasets = {'voc07'} ;
ex(3).C = 1 ;
ex(4) = ex(1) ;
ex(4).prefix = 'vlad-aug' ;
ex(4).opts = {...
'type', 'vlad', ...
'numWords', 256, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'xy', ...
'numPcaDimensions', 100, ...
'whitening', true, ...
'whiteningRegul', 0.01, ...
'renormalize', true, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(5) = ex(4) ;
ex(5).datasets = {'caltech101'} ;
ex(5).opts{end} = ex(2).opts{end} ;
ex(6) = ex(4) ;
ex(6).datasets = {'voc07'} ;
ex(6).C = 1 ;
ex(7) = ex(1) ;
ex(7).prefix = 'bovw-aug' ;
ex(7).opts = {...
'type', 'bovw', ...
'numWords', 4096, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'xy', ...
'numPcaDimensions', 100, ...
'whitening', true, ...
'whiteningRegul', 0.01, ...
'renormalize', true, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(8) = ex(7) ;
ex(8).datasets = {'caltech101'} ;
ex(8).opts{end} = ex(2).opts{end} ;
ex(9) = ex(7) ;
ex(9).datasets = {'voc07'} ;
ex(9).C = 1 ;
ex(10).prefix = 'fv' ;
ex(10).trainOpts = {'C', 10} ;
ex(10).datasets = {'fmd', 'scene67'} ;
ex(10).seed = 1 ;
ex(10).opts = {...
'type', 'fv', ...
'numWords', 256, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'none', ...
'numPcaDimensions', 80, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(11) = ex(10) ;
ex(11).datasets = {'caltech101'} ;
ex(11).opts{end} = @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(0:-.5:-3)) ;
ex(12) = ex(10) ;
ex(12).datasets = {'voc07'} ;
ex(12).C = 1 ;
ex(13).prefix = 'fv-sp' ;
ex(13).trainOpts = {'C', 10} ;
ex(13).datasets = {'fmd', 'scene67'} ;
ex(13).seed = 1 ;
ex(13).opts = {...
'type', 'fv', ...
'numWords', 256, ...
'layouts', {'1x1', '3x1'}, ...
'geometricExtension', 'none', ...
'numPcaDimensions', 80, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(14) = ex(13) ;
ex(14).datasets = {'caltech101'} ;
ex(14).opts{6} = {'1x1', '2x2'} ;
ex(14).opts{end} = @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(0:-.5:-3)) ;
ex(15) = ex(13) ;
ex(15).datasets = {'voc07'} ;
ex(15).C = 1 ;
if lite, tag = 'lite' ;
else, tag = 'ex' ; end
for i=1:numel(ex)
for j=1:numel(ex(i).datasets)
dataset = ex(i).datasets{j} ;
if ~isfield(ex(i), 'trainOpts') || ~iscell(ex(i).trainOpts)
ex(i).trainOpts = {} ;
end
traintest(...
'prefix', [tag '-' dataset '-' ex(i).prefix], ...
'seed', ex(i).seed, ...
'dataset', char(dataset), ...
'datasetDir', fullfile('data', dataset), ...
'lite', lite, ...
ex(i).trainOpts{:}, ...
'encoderParams', ex(i).opts) ;
end
end
% print HTML table
pf('<table>\n') ;
ph('method', 'VOC07', 'Caltech 101', 'Scene 67', 'FMD') ;
pr('FV', ...
ge([tag '-voc07-fv'],'ap11'), ...
ge([tag '-caltech101-fv']), ...
ge([tag '-scene67-fv']), ...
ge([tag '-fmd-fv'])) ;
pr('FV + aug.', ...
ge([tag '-voc07-fv-aug'],'ap11'), ...
ge([tag '-caltech101-fv-aug']), ...
ge([tag '-scene67-fv-aug']), ...
ge([tag '-fmd-fv-aug'])) ;
pr('FV + s.p.', ...
ge([tag '-voc07-fv-sp'],'ap11'), ...
ge([tag '-caltech101-fv-sp']), ...
ge([tag '-scene67-fv-sp']), ...
ge([tag '-fmd-fv-sp'])) ;
%pr('VLAD', ...
% ge([tag '-voc07-vlad'],'ap11'), ...
% ge([tag '-caltech101-vlad']), ...
% ge([tag '-scene67-vlad']), ...
% ge([tag '-fmd-vlad'])) ;
pr('VLAD + aug.', ...
ge([tag '-voc07-vlad-aug'],'ap11'), ...
ge([tag '-caltech101-vlad-aug']), ...
ge([tag '-scene67-vlad-aug']), ...
ge([tag '-fmd-vlad-aug'])) ;
%pr('VLAD+sp', ...
% ge([tag '-voc07-vlad-sp'],'ap11'), ...
% ge([tag '-caltech101-vlad-sp']), ...
% ge([tag '-scene67-vlad-sp']), ...
% ge([tag '-fmd-vlad-sp'])) ;
%pr('BOVW', ...
% ge([tag '-voc07-bovw'],'ap11'), ...
% ge([tag '-caltech101-bovw']), ...
% ge([tag '-scene67-bovw']), ...
% ge([tag '-fmd-bovw'])) ;
pr('BOVW + aug.', ...
ge([tag '-voc07-bovw-aug'],'ap11'), ...
ge([tag '-caltech101-bovw-aug']), ...
ge([tag '-scene67-bovw-aug']), ...
ge([tag '-fmd-bovw-aug'])) ;
%pr('BOVW+sp', ...
% ge([tag '-voc07-bovw-sp'],'ap11'), ...
% ge([tag '-caltech101-bovw-sp']), ...
% ge([tag '-scene67-bovw-sp']), ...
% ge([tag '-fmd-bovw-sp'])) ;
pf('</table>\n');
function pf(str)
fprintf(str) ;
function str = ge(name, format)
if nargin == 1, format = 'acc'; end
data = load(fullfile('data', name, 'result.mat')) ;
switch format
case 'acc'
str = sprintf('%.2f%% <span style="font-size:8px;">Acc</span>', mean(diag(data.confusion)) * 100) ;
case 'ap11'
str = sprintf('%.2f%% <span style="font-size:8px;">mAP</span>', mean(data.ap11) * 100) ;
end
function pr(varargin)
fprintf('<tr>') ;
for i=1:numel(varargin), fprintf('<td>%s</td>',varargin{i}) ; end
fprintf('</tr>\n') ;
function ph(varargin)
fprintf('<tr>') ;
for i=1:numel(varargin), fprintf('<th>%s</th>',varargin{i}) ; end
fprintf('</tr>\n') ;
|
github
|
sabbiu/ObjectDetection-master
|
getDenseSIFT.m
|
.m
|
ObjectDetection-master/Project-GUI/vlfeat-0.9.20/apps/recognition/getDenseSIFT.m
| 1,679 |
utf_8
|
2059c0a2a4e762226d89121408c6e51c
|
function features = getDenseSIFT(im, varargin)
% GETDENSESIFT Extract dense SIFT features
% FEATURES = GETDENSESIFT(IM) extract dense SIFT features from
% image IM.
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.scales = logspace(log10(1), log10(.25), 5) ;
opts.contrastthreshold = 0 ;
opts.step = 3 ;
opts.rootSift = false ;
opts.normalizeSift = true ;
opts.binSize = 8 ;
opts.geometry = [4 4 8] ;
opts.sigma = 0 ;
opts = vl_argparse(opts, varargin) ;
dsiftOpts = {'norm', 'fast', 'floatdescriptors', ...
'step', opts.step, ...
'size', opts.binSize, ...
'geometry', opts.geometry} ;
if size(im,3)>1, im = rgb2gray(im) ; end
im = im2single(im) ;
im = vl_imsmooth(im, opts.sigma) ;
for si = 1:numel(opts.scales)
im_ = imresize(im, opts.scales(si)) ;
[frames{si}, descrs{si}] = vl_dsift(im_, dsiftOpts{:}) ;
% root SIFT
if opts.rootSift
descrs{si} = sqrt(descrs{si}) ;
end
if opts.normalizeSift
descrs{si} = snorm(descrs{si}) ;
end
% zero low contrast descriptors
info.contrast{si} = frames{si}(3,:) ;
kill = info.contrast{si} < opts.contrastthreshold ;
descrs{si}(:,kill) = 0 ;
% store frames
frames{si}(1:2,:) = (frames{si}(1:2,:)-1) / opts.scales(si) + 1 ;
frames{si}(3,:) = opts.binSize / opts.scales(si) / 3 ;
end
features.frame = cat(2, frames{:}) ;
features.descr = cat(2, descrs{:}) ;
features.contrast = cat(2, info.contrast{:}) ;
function x = snorm(x)
x = bsxfun(@times, x, 1./max(1e-5,sqrt(sum(x.^2,1)))) ;
|
github
|
sabbiu/ObjectDetection-master
|
generate_bow.m
|
.m
|
ObjectDetection-master/Project-CLI/generate_bow.m
| 1,962 |
utf_8
|
d637d39a2cdd49b6c43fb6521174b402
|
%% Object Detection
% Sabbiu Shah, Sagar Adhikari, Samip Subedi
% Department of Electronics and Computer Engineering
% IOE, Pulchowk Campus
% 2016
%% ================ function that generates bag of words ==============
function [ histogram, bounding_rect] = generate_bow( image )
%generates bow for new image
bagg = 500;
I = imread(image);
level = graythresh(I);
bw = im2bw(I,level);
se = strel('line',11,90);
erodedBW = imerode(imcomplement(bw),se);
dilatedBW = imdilate(erodedBW,se);
col_info = any(dilatedBW,1);
row_info = any(dilatedBW,2);
min_x = 1; min_y = 1;
for i=1:size(col_info,2)
if(col_info(1,i) == 1)
if(min_x ==1 )
min_x = i;
end
max_x = i;
end
end
for i=1:size(row_info,1)
if(row_info(i,1) == 1)
if(min_y ==1 )
min_y = i;
end
max_y = i;
end
end
bounding_rect = [min_x, min_y, max_x-min_x, max_y-min_y];
I = imcrop(I,[min_x, min_y, max_x-min_x, max_y-min_y]);
imwrite(mat2gray(I),'temporary_crop.jpg');
descriptors = features_SIFT('temporary_crop.jpg');
load('cluster_centers.mat','centers');
descriptors = double(descriptors)/255;
% variable that stores cluster no.
cluster_no = [];
histogram = zeros(1,bagg);
for i=1:size(descriptors,1)
minimum = norm(descriptors(i,:)-centers(1,:));
index = 1;
for j=2:size(centers,1)
if(minimum > norm(descriptors(i,:)-centers(j,:)))
minimum = norm(descriptors(i,:)-centers(j,:));
index = j;
end
end
cluster_no = [cluster_no; index];
end
for i=1:size(cluster_no,1)
histogram(1,cluster_no(i,1)) = histogram(1,cluster_no(i,1)) + 1;
end
histogram = histogram/norm(histogram);
end
|
github
|
sabbiu/ObjectDetection-master
|
features_SIFT.m
|
.m
|
ObjectDetection-master/Project-CLI/features_SIFT.m
| 1,027 |
utf_8
|
53223ae2686f49c32df120fbc841dcc9
|
%% Object Detection
% Sabbiu Shah, Sagar Adhikari, Samip Subedi
% Department of Electronics and Computer Engineering
% IOE, Pulchowk Campus
% 2016
%% ================ SIFT_features function ===========================
function [ descriptor ] = features_SIFT( image_loc )
% This function returns descriptor for image using SIFT
peak_thresh = 0; % increase to limit; default is 0
edge_thresh = 10; % decrease to limit; default is 10
I = imread(image_loc);
% figure
% imshow(I);
if size(I,3)>1
I = rgb2gray(I);
end
I = single(I); % Convert to single precision floating point
[feature, descriptor] = vl_sift(I, ...
'PeakThresh', peak_thresh, ...
'edgethresh', edge_thresh );
% perm = randperm(size(feature,2)) ;
% sel = perm(1:50) ;
% h1 = vl_plotframe(feature(:,sel)) ;
% h2 = vl_plotframe(feature(:,sel)) ;
% set(h1,'color','k','linewidth',3) ;
% set(h2,'color','y','linewidth',2) ;
descriptor = transpose(descriptor);
end
|
github
|
sabbiu/ObjectDetection-master
|
kmeans.m
|
.m
|
ObjectDetection-master/Project-CLI/kmeans.m
| 1,652 |
utf_8
|
3d14ffd9f0a50969931cde873f4b27ec
|
%% Object Detection
% Sabbiu Shah, Sagar Adhikari, Samip Subedi
% Department of Electronics and Computer Engineering
% IOE, Pulchowk Campus
% 2016
%==================== K-means function ==============================
function [ center, number ] = kmeans( features, clusters, KMI )
%It is the implementation of kmeans algorithm
F = features;
K = clusters;
CENTS = F( ceil(rand(K,1)*size(F,1)) ,:); % Cluster Centers
cents_old = CENTS;
DAL = zeros(size(F,1),K+2); % Distances and Labels
fprintf('Doing...%2d',1);
for n = 1:KMI
fprintf('\b\b%2d',n);
for i = 1:size(F,1)
for j = 1:K
DAL(i,j) = norm(F(i,:) - CENTS(j,:));
end
[Distance, CN] = min(DAL(i,1:K)); % 1:K are Distance from Cluster Centers 1:K
DAL(i,K+1) = CN; % K+1 is Cluster Label
DAL(i,K+2) = Distance; % K+2 is Minimum Distance
end
for i = 1:K
A = (DAL(:,K+1) == i); % Cluster K Points
CENTS(i,:) = mean(F(A,:)); % New Cluster Centers
if sum(isnan(CENTS(:))) ~= 0 % If CENTS(i,:) Is Nan Then Replace It With Random Point
NC = find(isnan(CENTS(:,1)) == 1); % Find Nan Centers
for Ind = 1:size(NC,1)
CENTS(NC(Ind),:) = F(randi(size(F,1)),:);
end
end
end
check = cents_old - CENTS;
cents_old = CENTS;
check = abs(check);
val = max(max(check));
if(abs(val)<0.00001)
break;
end
end
center = CENTS;
number = DAL;
fprintf('\n');
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_compile.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/vl_compile.m
| 5,060 |
utf_8
|
978f5189bb9b2a16db3368891f79aaa6
|
function vl_compile(compiler)
% VL_COMPILE Compile VLFeat MEX files
% VL_COMPILE() uses MEX() to compile VLFeat MEX files. This command
% works only under Windows and is used to re-build problematic
% binaries. The preferred method of compiling VLFeat on both UNIX
% and Windows is through the provided Makefiles.
%
% VL_COMPILE() only compiles the MEX files and assumes that the
% VLFeat DLL (i.e. the file VLFEATROOT/bin/win{32,64}/vl.dll) has
% already been built. This file is built by the Makefiles.
%
% By default VL_COMPILE() assumes that Visual C++ is the active
% MATLAB compiler. VL_COMPILE('lcc') assumes that the active
% compiler is LCC instead (see MEX -SETUP). Unfortunately LCC does
% not seem to be able to compile the latest versions of VLFeat due
% to bugs in the support of 64-bit integers. Therefore it is
% recommended to use Visual C++ instead.
%
% See also: VL_NOPREFIX(), VL_HELP().
% Authors: Andrea Vedadli, Jonghyun Choi
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin < 1, compiler = 'visualc' ; end
switch lower(compiler)
case 'visualc'
fprintf('%s: assuming that Visual C++ is the active compiler\n', mfilename) ;
useLcc = false ;
case 'lcc'
fprintf('%s: assuming that LCC is the active compiler\n', mfilename) ;
warning('LCC may fail to compile VLFeat. See help vl_compile.') ;
useLcc = true ;
otherwise
error('Unknown compiler ''%s''.', compiler)
end
vlDir = vl_root ;
toolboxDir = fullfile(vlDir, 'toolbox') ;
switch computer
case 'PCWIN'
fprintf('%s: compiling for PCWIN (32 bit)\n', mfilename);
mexwDir = fullfile(toolboxDir, 'mex', 'mexw32') ;
binwDir = fullfile(vlDir, 'bin', 'win32') ;
case 'PCWIN64'
fprintf('%s: compiling for PCWIN64 (64 bit)\n', mfilename);
mexwDir = fullfile(toolboxDir, 'mex', 'mexw64') ;
binwDir = fullfile(vlDir, 'bin', 'win64') ;
otherwise
error('The architecture is neither PCWIN nor PCWIN64. See help vl_compile.') ;
end
impLibPath = fullfile(binwDir, 'vl.lib') ;
libDir = fullfile(binwDir, 'vl.dll') ;
mkd(mexwDir) ;
% find the subdirectories of toolbox that we should process
subDirs = dir(toolboxDir) ;
subDirs = subDirs([subDirs.isdir]) ;
discard = regexp({subDirs.name}, '^(.|..|noprefix|mex.*)$', 'start') ;
keep = cellfun('isempty', discard) ;
subDirs = subDirs(keep) ;
subDirs = {subDirs.name} ;
% Copy support files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if ~exist(fullfile(binwDir, 'vl.dll'))
error('The VLFeat DLL (%s) could not be found. See help vl_compile.', ...
fullfile(binwDir, 'vl.dll')) ;
end
tmp = dir(fullfile(binwDir, '*.dll')) ;
supportFileNames = {tmp.name} ;
for fi = 1:length(supportFileNames)
name = supportFileNames{fi} ;
cp(fullfile(binwDir, name), ...
fullfile(mexwDir, name) ) ;
end
% Ensure implib for LCC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if useLcc
lccImpLibDir = fullfile(mexwDir, 'lcc') ;
lccImpLibPath = fullfile(lccImpLibDir, 'VL.lib') ;
lccRoot = fullfile(matlabroot, 'sys', 'lcc', 'bin') ;
lccImpExePath = fullfile(lccRoot, 'lcc_implib.exe') ;
mkd(lccImpLibDir) ;
cp(fullfile(binwDir, 'vl.dll'), fullfile(lccImpLibDir, 'vl.dll')) ;
cmd = ['"' lccImpExePath '"', ' -u ', '"' fullfile(lccImpLibDir, 'vl.dll') '"'] ;
fprintf('Running:\n> %s\n', cmd) ;
curPath = pwd ;
try
cd(lccImpLibDir) ;
[d,w] = system(cmd) ;
if d, error(w); end
cd(curPath) ;
catch
cd(curPath) ;
error(lasterr) ;
end
end
% Compile each mex file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for i = 1:length(subDirs)
thisDir = fullfile(toolboxDir, subDirs{i}) ;
fileNames = ls(fullfile(thisDir, '*.c'));
for f = 1:size(fileNames,1)
fileName = fileNames(f, :) ;
sp = strfind(fileName, ' ');
if length(sp) > 0, fileName = fileName(1:sp-1); end
filePath = fullfile(thisDir, fileName);
fprintf('MEX %s\n', filePath);
dot = strfind(fileName, '.');
mexFile = fullfile(mexwDir, [fileName(1:dot) 'dll']);
if exist(mexFile)
delete(mexFile)
end
cmd = {['-I' toolboxDir], ...
['-I' vlDir], ...
'-O', ...
'-outdir', mexwDir, ...
filePath } ;
if useLcc
cmd{end+1} = lccImpLibPath ;
else
cmd{end+1} = impLibPath ;
end
mex(cmd{:}) ;
end
end
% --------------------------------------------------------------------
function cp(src,dst)
% --------------------------------------------------------------------
if ~exist(dst,'file')
fprintf('Copying ''%s'' to ''%s''.\n', src,dst) ;
copyfile(src,dst) ;
end
% --------------------------------------------------------------------
function mkd(dst)
% --------------------------------------------------------------------
if ~exist(dst, 'dir')
fprintf('Creating directory ''%s''.', dst) ;
mkdir(dst) ;
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_noprefix.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/vl_noprefix.m
| 1,875 |
utf_8
|
97d8755f0ba139ac1304bc423d3d86d3
|
function vl_noprefix
% VL_NOPREFIX Create a prefix-less version of VLFeat commands
% VL_NOPREFIX() creats prefix-less stubs for VLFeat functions
% (e.g. SIFT for VL_SIFT). This function is seldom used as the stubs
% are included in the VLFeat binary distribution anyways. Moreover,
% on UNIX platforms, the stubs are generally constructed by the
% Makefile.
%
% See also: VL_COMPILE(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
root = fileparts(which(mfilename)) ;
list = listMFilesX(root);
outDir = fullfile(root, 'noprefix') ;
if ~exist(outDir, 'dir')
mkdir(outDir) ;
end
for li = 1:length(list)
name = list(li).name(1:end-2) ; % remove .m
nname = name(4:end) ; % remove vl_
stubPath = fullfile(outDir, [nname '.m']) ;
fout = fopen(stubPath, 'w') ;
fprintf('Creating stub %s for %s\n', stubPath, nname) ;
fprintf(fout, 'function varargout = %s(varargin)\n', nname) ;
fprintf(fout, '%% %s Stub for %s\n', upper(nname), upper(name)) ;
fprintf(fout, '[varargout{1:nargout}] = %s(varargin{:})\n', name) ;
fclose(fout) ;
end
end
function list = listMFilesX(root)
list = struct('name', {}, 'path', {}) ;
files = dir(root) ;
for fi = 1:length(files)
name = files(fi).name ;
if files(fi).isdir
if any(regexp(name, '^(\.|\.\.|noprefix)$'))
continue ;
else
tmp = listMFilesX(fullfile(root, name)) ;
list = [list, tmp] ;
end
end
if any(regexp(name, '^vl_(demo|test).*m$'))
continue ;
elseif any(regexp(name, '^vl_(demo|setup|compile|help|root|noprefix)\.m$'))
continue ;
elseif any(regexp(name, '\.m$'))
list(end+1) = struct(...
'name', {name}, ...
'path', {fullfile(root, name)}) ;
end
end
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_pegasos.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/misc/vl_pegasos.m
| 2,837 |
utf_8
|
d5e0915c439ece94eb5597a07090b67d
|
% VL_PEGASOS [deprecated]
% VL_PEGASOS is deprecated. Please use VL_SVMTRAIN() instead.
function [w b info] = vl_pegasos(X,Y,LAMBDA, varargin)
% Verbose not supported
if (sum(strcmpi('Verbose',varargin)))
varargin(find(strcmpi('Verbose',varargin),1))=[];
fprintf('Option VERBOSE is no longer supported.\n');
end
% DiagnosticCallRef not supported
if (sum(strcmpi('DiagnosticCallRef',varargin)))
varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[];
varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[];
fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n');
end
% different default value for MaxIterations
if (sum(strcmpi('MaxIterations',varargin)) == 0)
varargin{end+1} = 'MaxIterations';
varargin{end+1} = ceil(10/LAMBDA);
end
% different default value for BiasMultiplier
if (sum(strcmpi('BiasMultiplier',varargin)) == 0)
varargin{end+1} = 'BiasMultiplier';
varargin{end+1} = 0;
end
% parameters for vl_maketrainingset
setvarargin = {};
if (sum(strcmpi('HOMKERMAP',varargin)))
setvarargin{end+1} = 'HOMKERMAP';
setvarargin{end+1} = varargin{find(strcmpi('HOMKERMAP',varargin),1)+1};
varargin(find(strcmpi('HOMKERMAP',varargin),1)+1)=[];
varargin(find(strcmpi('HOMKERMAP',varargin),1))=[];
end
if (sum(strcmpi('KChi2',varargin)))
setvarargin{end+1} = 'KChi2';
varargin(find(strcmpi('KChi2',varargin),1))=[];
end
if (sum(strcmpi('KINTERS',varargin)))
setvarargin{end+1} = 'KINTERS';
varargin(find(strcmpi('KINTERS',varargin),1))=[];
end
if (sum(strcmpi('KL1',varargin)))
setvarargin{end+1} = 'KL1';
varargin(find(strcmpi('KL1',varargin),1))=[];
end
if (sum(strcmpi('KJS',varargin)))
setvarargin{end+1} = 'KJS';
varargin(find(strcmpi('KJS',varargin),1))=[];
end
if (sum(strcmpi('Period',varargin)))
setvarargin{end+1} = 'Period';
setvarargin{end+1} = varargin{find(strcmpi('Period',varargin),1)+1};
varargin(find(strcmpi('Period',varargin),1)+1)=[];
varargin(find(strcmpi('Period',varargin),1))=[];
end
if (sum(strcmpi('Window',varargin)))
setvarargin{end+1} = 'Window';
setvarargin{end+1} = varargin{find(strcmpi('Window',varargin),1)+1};
varargin(find(strcmpi('Window',varargin),1)+1)=[];
varargin(find(strcmpi('Window',varargin),1))=[];
end
if (sum(strcmpi('Gamma',varargin)))
setvarargin{end+1} = 'Gamma';
setvarargin{end+1} = varargin{find(strcmpi('Gamma',varargin),1)+1};
varargin(find(strcmpi('Gamma',varargin),1)+1)=[];
varargin(find(strcmpi('Gamma',varargin),1))=[];
end
setvarargin{:}
DATA = vl_maketrainingset(double(X),int8(Y),setvarargin{:});
DATA
[w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:});
fprintf('\n vl_pegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n');
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_svmpegasos.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/misc/vl_svmpegasos.m
| 1,178 |
utf_8
|
009c2a2b87a375d529ed1a4dbe3af59f
|
% VL_SVMPEGASOS [deprecated]
% VL_SVMPEGASOS is deprecated. Please use VL_SVMTRAIN() instead.
function [w b info] = vl_svmpegasos(DATA,LAMBDA, varargin)
% Verbose not supported
if (sum(strcmpi('Verbose',varargin)))
varargin(find(strcmpi('Verbose',varargin),1))=[];
fprintf('Option VERBOSE is no longer supported.\n');
end
% DiagnosticCallRef not supported
if (sum(strcmpi('DiagnosticCallRef',varargin)))
varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[];
varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[];
fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n');
end
% different default value for MaxIterations
if (sum(strcmpi('MaxIterations',varargin)) == 0)
varargin{end+1} = 'MaxIterations';
varargin{end+1} = ceil(10/LAMBDA);
end
% different default value for BiasMultiplier
if (sum(strcmpi('BiasMultiplier',varargin)) == 0)
varargin{end+1} = 'BiasMultiplier';
varargin{end+1} = 0;
end
[w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:});
fprintf('\n vl_svmpegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n');
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_override.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/misc/vl_override.m
| 4,654 |
utf_8
|
e233d2ecaeb68f56034a976060c594c5
|
function config = vl_override(config,update,varargin)
% VL_OVERRIDE Override structure subset
% CONFIG = VL_OVERRIDE(CONFIG, UPDATE) copies recursively the fileds
% of the structure UPDATE to the corresponding fields of the
% struture CONFIG.
%
% Usually CONFIG is interpreted as a list of paramters with their
% default values and UPDATE as a list of new paramete values.
%
% VL_OVERRIDE(..., 'Warn') prints a warning message whenever: (i)
% UPDATE has a field not found in CONFIG, or (ii) non-leaf values of
% CONFIG are overwritten.
%
% VL_OVERRIDE(..., 'Skip') skips fields of UPDATE that are not found
% in CONFIG instead of copying them.
%
% VL_OVERRIDE(..., 'CaseI') matches field names in a
% case-insensitive manner.
%
% Remark::
% Fields are copied at the deepest possible level. For instance,
% if CONFIG has fields A.B.C1=1 and A.B.C2=2, and if UPDATE is the
% structure A.B.C1=3, then VL_OVERRIDE() returns a strucuture with
% fields A.B.C1=3, A.B.C2=2. By contrast, if UPDATE is the
% structure A.B=4, then the field A.B is copied, and VL_OVERRIDE()
% returns the structure A.B=4 (specifying 'Warn' would warn about
% the fact that the substructure B.C1, B.C2 is being deleted).
%
% Remark::
% Two fields are matched if they correspond exactly. Specifically,
% two fileds A(IA).(FA) and B(IA).FB of two struct arrays A and B
% match if, and only if, (i) A and B have the same dimensions,
% (ii) IA == IB, and (iii) FA == FB.
%
% See also: VL_ARGPARSE(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
warn = false ;
skip = false ;
err = false ;
casei = false ;
if length(varargin) == 1 & ~ischar(varargin{1})
% legacy
warn = 1 ;
end
if ~warn & length(varargin) > 0
for i=1:length(varargin)
switch lower(varargin{i})
case 'warn'
warn = true ;
case 'skip'
skip = true ;
case 'err'
err = true ;
case 'argparse'
argparse = true ;
case 'casei'
casei = true ;
otherwise
error(sprintf('Unknown option ''%s''.',varargin{i})) ;
end
end
end
% if CONFIG is not a struct array just copy UPDATE verbatim
if ~isstruct(config)
config = update ;
return ;
end
% if CONFIG is a struct array but UPDATE is not, no match can be
% established and we simply copy UPDATE verbatim
if ~isstruct(update)
config = update ;
return ;
end
% if CONFIG and UPDATE are both struct arrays, but have different
% dimensions then nom atch can be established and we simply copy
% UPDATE verbatim
if numel(update) ~= numel(config)
config = update ;
return ;
end
% if CONFIG and UPDATE are both struct arrays of the same
% dimension, we override recursively each field
for idx=1:numel(update)
fields = fieldnames(update) ;
for i = 1:length(fields)
updateFieldName = fields{i} ;
if casei
configFieldName = findFieldI(config, updateFieldName) ;
else
configFieldName = findField(config, updateFieldName) ;
end
if ~isempty(configFieldName)
config(idx).(configFieldName) = ...
vl_override(config(idx).(configFieldName), ...
update(idx).(updateFieldName)) ;
else
if warn
warning(sprintf('copied field ''%s'' which is in UPDATE but not in CONFIG', ...
updateFieldName)) ;
end
if err
error(sprintf('The field ''%s'' is in UPDATE but not in CONFIG', ...
updateFieldName)) ;
end
if skip
if warn
warning(sprintf('skipping field ''%s'' which is in UPDATE but not in CONFIG', ...
updateFieldName)) ;
end
continue ;
end
config(idx).(updateFieldName) = update(idx).(updateFieldName) ;
end
end
end
% --------------------------------------------------------------------
function field = findFieldI(S, matchField)
% --------------------------------------------------------------------
field = '' ;
fieldNames = fieldnames(S) ;
for fi=1:length(fieldNames)
if strcmpi(fieldNames{fi}, matchField)
field = fieldNames{fi} ;
end
end
% --------------------------------------------------------------------
function field = findField(S, matchField)
% --------------------------------------------------------------------
field = '' ;
fieldNames = fieldnames(S) ;
for fi=1:length(fieldNames)
if strcmp(fieldNames{fi}, matchField)
field = fieldNames{fi} ;
end
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_quickvis.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/quickshift/vl_quickvis.m
| 3,696 |
utf_8
|
27f199dad4c5b9c192a5dd3abc59f9da
|
function [Iedge dists map gaps] = vl_quickvis(I, ratio, kernelsize, maxdist, maxcuts)
% VL_QUICKVIS Create an edge image from a Quickshift segmentation.
% IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) creates an edge
% stability image from a Quickshift segmentation. RATIO controls the tradeoff
% between color consistency and spatial consistency (See VL_QUICKSEG) and
% KERNELSIZE controls the bandwidth of the density estimator (See VL_QUICKSEG,
% VL_QUICKSHIFT). MAXDIST is the maximum distance between neighbors which
% increase the density.
%
% VL_QUICKVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at
% most MAXCUTS segmentations. The edges between regions in each of these
% segmentations are labeled in IEDGE, where the label corresponds to the
% largest DIST which preserves the edge.
%
% [IEDGE,DISTS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) also
% returns the DIST thresholds that were chosen.
%
% IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, DISTS) will use the DISTS
% specified
%
% [IEDGE,DISTS,MAP,GAPS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS)
% also returns the MAP and GAPS from VL_QUICKSHIFT.
%
% See Also: VL_QUICKSHIFT(), VL_QUICKSEG(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin == 4
dists = maxdist;
maxdist = max(dists);
[Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist);
else
[Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist);
dists = unique(floor(gaps(:)));
dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh
if length(dists) > maxcuts
ind = round(linspace(1,length(dists), maxcuts));
dists = dists(ind);
end
end
[Iedge dists] = mapvis(map, gaps, dists);
function [Iedge dists] = mapvis(map, gaps, maxdist, maxcuts)
% MAPVIS Create an edge image from a Quickshift segmentation.
% IEDGE = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) creates an edge
% stability image from a Quickshift segmentation. MAXDIST is the maximum
% distance between neighbors which increase the density.
%
% MAPVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at most
% MAXCUTS segmentations. The edges between regions in each of these
% segmentations are labeled in IEDGE, where the label corresponds to the
% largest DIST which preserves the edge.
%
% [IEDGE,DISTS] = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) also returns the DIST
% thresholds that were chosen.
%
% IEDGE = MAPVIS(MAP, GAPS, DISTS) will use the DISTS specified
%
% See Also: VL_QUICKVIS, VL_QUICKSHIFT, VL_QUICKSEG
if nargin == 3
dists = maxdist;
maxdist = max(dists);
else
dists = unique(floor(gaps(:)));
dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh
% throw away min region size instead of maxdist?
ind = find(dists < maxdist);
dists = dists(ind);
if length(dists) > maxcuts
ind = round(linspace(1,length(dists), maxcuts));
dists = dists(ind);
end
end
Iedge = zeros(size(map));
for i = 1:length(dists)
s = find(gaps >= dists(i));
mapdist = map;
mapdist(s) = s;
[mapped labels] = vl_flatmap(mapdist);
fprintf('%d/%d %d regions\n', i, length(dists), length(unique(mapped)))
borders = getborders(mapped);
Iedge(borders) = dists(i);
%Iedge(borders) = Iedge(borders) + 1;
%Iedge(borders) = i;
end
%%%%%%%%% GETBORDERS
function borders = getborders(map)
dx = conv2(map, [-1 1], 'same');
dy = conv2(map, [-1 1]', 'same');
borders = find(dx ~= 0 | dy ~= 0);
|
github
|
sabbiu/ObjectDetection-master
|
vl_demo_aib.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/demo/vl_demo_aib.m
| 2,928 |
utf_8
|
590c6db09451ea608d87bfd094662cac
|
function vl_demo_aib
% VL_DEMO_AIB Test Agglomerative Information Bottleneck (AIB)
D = 4 ;
K = 20 ;
randn('state',0) ;
rand('state',0) ;
X1 = randn(2,300) ; X1(1,:) = X1(1,:) + 2 ;
X2 = randn(2,300) ; X2(1,:) = X2(1,:) - 2 ;
X3 = randn(2,300) ; X3(2,:) = X3(2,:) + 2 ;
figure(1) ; clf ; hold on ;
vl_plotframe(X1,'color','r') ;
vl_plotframe(X2,'color','g') ;
vl_plotframe(X3,'color','b') ;
axis equal ;
xlim([-4 4]);
ylim([-4 4]);
axis off ;
rectangle('position',D*[-1 -1 2 2])
vl_demo_print('aib_basic_data', .6) ;
C = 1:K*K ;
Pcx = zeros(3,K*K) ;
f1 = quantize(X1,D,K) ;
f2 = quantize(X2,D,K) ;
f3 = quantize(X3,D,K) ;
Pcx(1,:) = vl_binsum(Pcx(1,:), ones(size(f1)), f1) ;
Pcx(2,:) = vl_binsum(Pcx(2,:), ones(size(f2)), f2) ;
Pcx(3,:) = vl_binsum(Pcx(3,:), ones(size(f3)), f3) ;
Pcx = Pcx / sum(Pcx(:)) ;
[parents, cost] = vl_aib(Pcx) ;
cutsize = [K*K, 10, 3, 2, 1] ;
for i=1:length(cutsize)
[cut,map,short] = vl_aibcut(parents, cutsize(i)) ;
parents_cut(short > 0) = parents(short(short > 0)) ;
C = short(1:K*K+1) ; [drop1,drop2,C] = unique(C) ;
figure(i+1) ; clf ;
plotquantization(D,K,C) ; hold on ;
%plottree(D,K,parents_cut) ;
axis equal ;
axis off ;
title(sprintf('%d clusters', cutsize(i))) ;
vl_demo_print(sprintf('aib_basic_clust_%d',i),.6) ;
end
% --------------------------------------------------------------------
function f = quantize(X,D,K)
% --------------------------------------------------------------------
d = 2*D / K ;
j = round((X(1,:) + D) / d) ;
i = round((X(2,:) + D) / d) ;
j = max(min(j,K),1) ;
i = max(min(i,K),1) ;
f = sub2ind([K K],i,j) ;
% --------------------------------------------------------------------
function [i,j] = plotquantization(D,K,C)
% --------------------------------------------------------------------
hold on ;
cl = [[.3 .3 .3] ; .5*hsv(max(C)-1)+.5] ;
d = 2*D / K ;
for i=0:K-1
for j=0:K-1
patch(d*(j+[0 1 1 0])-D, ...
d*(i+[0 0 1 1])-D, ...
cl(C(j*K+i+1),:)) ;
end
end
% --------------------------------------------------------------------
function h = plottree(D,K,parents)
% --------------------------------------------------------------------
d = 2*D / K ;
C = zeros(2,2*K*K-1)+NaN ;
N = zeros(1,2*K*K-1) ;
for i=0:K-1
for j=0:K-1
C(:,j*K+i+1) = [d*j-D; d*i-D]+d/2 ;
N(:,j*K+i+1) = 1 ;
end
end
for i=1:length(parents)
p = parents(i) ;
if p==0, continue ; end;
if all(isnan(C(:,i))), continue; end
if all(isnan(C(:,p)))
C(:,p) = C(:,i) / N(i) ;
else
C(:,p) = C(:,p) + C(:,i) / N(i) ;
end
N(p) = N(p) + 1 ;
end
C(1,:) = C(1,:) ./ N ;
C(2,:) = C(2,:) ./ N ;
xt = zeros(3, 2*length(parents)-1)+NaN ;
yt = zeros(3, 2*length(parents)-1)+NaN ;
for i=1:length(parents)
p = parents(i) ;
if p==0, continue ; end;
xt(1,i) = C(1,i) ; xt(2,i) = C(1,p) ;
yt(1,i) = C(2,i) ; yt(2,i) = C(2,p) ;
end
h=line(xt(:),yt(:),'linestyle','-','marker','.','linewidth',3) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_demo_alldist.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/demo/vl_demo_alldist.m
| 5,460 |
utf_8
|
6d008a64d93445b9d7199b55d58db7eb
|
function vl_demo_alldist
%
numRepetitions = 3 ;
numDimensions = 1000 ;
numSamplesRange = [300] ;
settingsRange = {{'alldist2', 'double', 'l2', }, ...
{'alldist', 'double', 'l2', 'nosimd'}, ...
{'alldist', 'double', 'l2' }, ...
{'alldist2', 'single', 'l2', }, ...
{'alldist', 'single', 'l2', 'nosimd'}, ...
{'alldist', 'single', 'l2' }, ...
{'alldist2', 'double', 'l1', }, ...
{'alldist', 'double', 'l1', 'nosimd'}, ...
{'alldist', 'double', 'l1' }, ...
{'alldist2', 'single', 'l1', }, ...
{'alldist', 'single', 'l1', 'nosimd'}, ...
{'alldist', 'single', 'l1' }, ...
{'alldist2', 'double', 'chi2', }, ...
{'alldist', 'double', 'chi2', 'nosimd'}, ...
{'alldist', 'double', 'chi2' }, ...
{'alldist2', 'single', 'chi2', }, ...
{'alldist', 'single', 'chi2', 'nosimd'}, ...
{'alldist', 'single', 'chi2' }, ...
{'alldist2', 'double', 'hell', }, ...
{'alldist', 'double', 'hell', 'nosimd'}, ...
{'alldist', 'double', 'hell' }, ...
{'alldist2', 'single', 'hell', }, ...
{'alldist', 'single', 'hell', 'nosimd'}, ...
{'alldist', 'single', 'hell' }, ...
{'alldist2', 'double', 'kl2', }, ...
{'alldist', 'double', 'kl2', 'nosimd'}, ...
{'alldist', 'double', 'kl2' }, ...
{'alldist2', 'single', 'kl2', }, ...
{'alldist', 'single', 'kl2', 'nosimd'}, ...
{'alldist', 'single', 'kl2' }, ...
{'alldist2', 'double', 'kl1', }, ...
{'alldist', 'double', 'kl1', 'nosimd'}, ...
{'alldist', 'double', 'kl1' }, ...
{'alldist2', 'single', 'kl1', }, ...
{'alldist', 'single', 'kl1', 'nosimd'}, ...
{'alldist', 'single', 'kl1' }, ...
{'alldist2', 'double', 'kchi2', }, ...
{'alldist', 'double', 'kchi2', 'nosimd'}, ...
{'alldist', 'double', 'kchi2' }, ...
{'alldist2', 'single', 'kchi2', }, ...
{'alldist', 'single', 'kchi2', 'nosimd'}, ...
{'alldist', 'single', 'kchi2' }, ...
{'alldist2', 'double', 'khell', }, ...
{'alldist', 'double', 'khell', 'nosimd'}, ...
{'alldist', 'double', 'khell' }, ...
{'alldist2', 'single', 'khell', }, ...
{'alldist', 'single', 'khell', 'nosimd'}, ...
{'alldist', 'single', 'khell' }, ...
} ;
%settingsRange = settingsRange(end-5:end) ;
styles = {} ;
for marker={'x','+','.','*','o'}
for color={'r','g','b','k','y'}
styles{end+1} = {'color', char(color), 'marker', char(marker)} ;
end
end
for ni=1:length(numSamplesRange)
for ti=1:length(settingsRange)
tocs = [] ;
for ri=1:numRepetitions
rand('state',ri) ;
randn('state',ri) ;
numSamples = numSamplesRange(ni) ;
settings = settingsRange{ti} ;
[tocs(end+1), D] = run_experiment(numDimensions, ...
numSamples, ...
settings) ;
end
means(ni,ti) = mean(tocs) ;
stds(ni,ti) = std(tocs) ;
if mod(ti-1,3) == 0
D0 = D ;
else
err = max(abs(D(:)-D0(:))) ;
fprintf('err %f\n', err) ;
if err > 1, keyboard ; end
end
end
end
if 0
figure(1) ; clf ; hold on ;
numStyles = length(styles) ;
for ti=1:length(settingsRange)
si = mod(ti - 1, numStyles) + 1 ;
h(ti) = plot(numSamplesRange, means(:,ti), styles{si}{:}) ;
leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ;
errorbar(numSamplesRange, means(:,ti), stds(:,ti), 'linestyle', 'none') ;
end
end
for ti=1:length(settingsRange)
leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ;
end
figure(1) ; clf ;
barh(means(end,:)) ;
set(gca,'ytick', 1:length(leg), 'yticklabel', leg,'ydir','reverse') ;
xlabel('Time [s]') ;
function [elaps, D] = run_experiment(numDimensions, numSamples, settings)
distType = 'l2' ;
algType = 'alldist' ;
classType = 'double' ;
useSimd = true ;
for si=1:length(settings)
arg = settings{si} ;
switch arg
case {'l1', 'l2', 'chi2', 'hell', 'kl2', 'kl1', 'kchi2', 'khell'}
distType = arg ;
case {'alldist', 'alldist2'}
algType = arg ;
case {'single', 'double'}
classType = arg ;
case 'simd'
useSimd = true ;
case 'nosimd'
useSimd = false ;
otherwise
assert(false) ;
end
end
X = rand(numDimensions, numSamples) ;
X(X < .3) = 0 ;
switch classType
case 'double'
case 'single'
X = single(X) ;
end
vl_simdctrl(double(useSimd)) ;
switch algType
case 'alldist'
tic ; D = vl_alldist(X, distType) ; elaps = toc ;
case 'alldist2'
tic ; D = vl_alldist2(X, distType) ; elaps = toc ;
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_demo_ikmeans.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/demo/vl_demo_ikmeans.m
| 774 |
utf_8
|
17ff0bb7259d390fb4f91ea937ba7de0
|
function vl_demo_ikmeans()
% VL_DEMO_IKMEANS
numData = 10000 ;
dimension = 2 ;
data = uint8(255*rand(dimension,numData)) ;
numClusters = 3^3 ;
[centers, assignments] = vl_ikmeans(data, numClusters);
figure(1) ; clf ; axis off ;
plotClusters(data, centers, assignments) ;
vl_demo_print('ikmeans_2d',0.6);
[tree, assignments] = vl_hikmeans(data,3,numClusters) ;
figure(2) ; clf ; axis off ;
plotClusters(data, [], [4 2 1] * double(assignments)) ;
vl_demo_print('hikmeans_2d',0.6);
function plotClusters(data, centers, assignments)
hold on ;
cc=jet(double(max(assignments(:))));
for i=1:max(assignments(:))
plot(data(1,assignments == i),data(2,assignments == i),'.','color',cc(i,:));
end
if ~isempty(centers)
plot(centers(1,:),centers(2,:),'k.','MarkerSize',20)
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_demo_svm.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/demo/vl_demo_svm.m
| 1,235 |
utf_8
|
7cf6b3504e4fc2cbd10ff3fec6e331a7
|
% VL_DEMO_SVM Demo: SVM: 2D linear learning
function vl_demo_svm
y=[];X=[];
% Load training data X and their labels y
load('vl_demo_svm_data.mat')
Xp = X(:,y==1);
Xn = X(:,y==-1);
figure
plot(Xn(1,:),Xn(2,:),'*r')
hold on
plot(Xp(1,:),Xp(2,:),'*b')
axis equal ;
vl_demo_print('svm_training') ;
% Parameters
lambda = 0.01 ; % Regularization parameter
maxIter = 1000 ; % Maximum number of iterations
energy = [] ;
% Diagnostic function
function diagnostics(svm)
energy = [energy [svm.objective ; svm.dualObjective ; svm.dualityGap ] ] ;
end
% Training the SVM
energy = [] ;
[w b info] = vl_svmtrain(X, y, lambda,...
'MaxNumIterations',maxIter,...
'DiagnosticFunction',@diagnostics,...
'DiagnosticFrequency',1)
% Visualisation
eq = [num2str(w(1)) '*x+' num2str(w(2)) '*y+' num2str(b)];
line = ezplot(eq, [-0.9 0.9 -0.9 0.9]);
set(line, 'Color', [0 0.8 0],'linewidth', 2);
vl_demo_print('svm_training_result') ;
figure
hold on
plot(energy(1,:),'--b') ;
plot(energy(2,:),'-.g') ;
plot(energy(3,:),'r') ;
legend('Primal objective','Dual objective','Duality gap')
xlabel('Diagnostics iteration')
ylabel('Energy')
vl_demo_print('svm_energy') ;
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_demo_kdtree_sift.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/demo/vl_demo_kdtree_sift.m
| 6,832 |
utf_8
|
e676f80ac330a351f0110533c6ebba89
|
function vl_demo_kdtree_sift
% VL_DEMO_KDTREE_SIFT
% Demonstrates the use of a kd-tree forest to match SIFT
% features. If FLANN is present, this function runs a comparison
% against it.
% AUTORIGHS
rand('state',0) ;
randn('state',0);
do_median = 0 ;
do_mean = 1 ;
% try to setup flann
if ~exist('flann_search', 'file')
if exist(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab'))
addpath(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab')) ;
end
end
do_flann = exist('nearest_neighbors') == 3 ;
if ~do_flann
warning('FLANN not found. Comparison disabled.') ;
end
maxNumComparisonsRange = [1 10 50 100 200 300 400] ;
numTreesRange = [1 2 5 10] ;
% get data (SIFT features)
im1 = imread(fullfile(vl_root, 'data', 'roofs1.jpg')) ;
im2 = imread(fullfile(vl_root, 'data', 'roofs2.jpg')) ;
im1 = single(rgb2gray(im1)) ;
im2 = single(rgb2gray(im2)) ;
[f1,d1] = vl_sift(im1,'firstoctave',-1,'floatdescriptors','verbose') ;
[f2,d2] = vl_sift(im2,'firstoctave',-1,'floatdescriptors','verbose') ;
% add some noise to make matches unique
d1 = single(d1) + rand(size(d1)) ;
d2 = single(d2) + rand(size(d2)) ;
% match exhaustively to get the ground truth
elapsedDirect = tic ;
D = vl_alldist(d1,d2) ;
[drop, best] = min(D, [], 1) ;
elapsedDirect = toc(elapsedDirect) ;
for ti=1:length(numTreesRange)
for vi=1:length(maxNumComparisonsRange)
v = maxNumComparisonsRange(vi) ;
t = numTreesRange(ti) ;
if do_median
tic ;
kdtree = vl_kdtreebuild(d1, ...
'verbose', ...
'thresholdmethod', 'median', ...
'numtrees', t) ;
[i, d] = vl_kdtreequery(kdtree, d1, d2, ...
'verbose', ...
'maxcomparisons',v) ;
elapsedKD_median(vi,ti) = toc ;
errors_median(vi,ti) = sum(double(i) ~= best) / length(best) ;
errorsD_median(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
if do_mean
tic ;
kdtree = vl_kdtreebuild(d1, ...
'verbose', ...
'thresholdmethod', 'mean', ...
'numtrees', t) ;
%kdtree = readflann(kdtree, '/tmp/flann.txt') ;
%checkx(kdtree, d1, 1, 1) ;
[i, d] = vl_kdtreequery(kdtree, d1, d2, ...
'verbose', ...
'maxcomparisons', v) ;
elapsedKD_mean(vi,ti) = toc ;
errors_mean(vi,ti) = sum(double(i) ~= best) / length(best) ;
errorsD_mean(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
if do_flann
tic ;
[i, d] = flann_search(d1, d2, 1, struct('algorithm','kdtree', ...
'trees', t, ...
'checks', v));
ifla = i ;
elapsedKD_flann(vi,ti) = toc;
errors_flann(vi,ti) = sum(i ~= best) / length(best) ;
errorsD_flann(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
end
end
figure(1) ; clf ;
leg = {} ;
hnd = [] ;
sty = {{'color','r'},{'color','g'},...
{'color','b'},{'color','c'},...
{'color','k'}} ;
for ti=1:length(numTreesRange)
s = sty{mod(ti,length(sty))+1} ;
if do_median
h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errors_median(:,ti),'-*',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h1 ;
end
if do_mean
h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errors_mean(:,ti), '-o',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h2 ;
end
if do_flann
h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errors_flann(:,ti), '+--',s{:}) ; hold on ;
leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h3 ;
end
end
set([hnd], 'linewidth', 2) ;
xlabel('speedup over linear search (log times)') ;
ylabel('percentage of incorrect matches (%)') ;
h=legend(hnd, leg{:}, 'location', 'southeast') ;
set(h,'fontsize',8) ;
grid on ;
axis square ;
vl_demo_print('kdtree_sift_incorrect',.6) ;
figure(2) ; clf ;
leg = {} ;
hnd = [] ;
for ti=1:length(numTreesRange)
s = sty{mod(ti,length(sty))+1} ;
if do_median
h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errorsD_median(:,ti),'*-',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h1 ;
end
if do_mean
h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errorsD_mean(:,ti), 'o-',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h2 ;
end
if do_flann
h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errorsD_flann(:,ti), '+--',s{:}) ; hold on ;
leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h3 ;
end
end
set([hnd], 'linewidth', 2) ;
xlabel('speedup over linear search (log times)') ;
ylabel('relative overestimation of minmium distannce (%)') ;
h=legend(hnd, leg{:}, 'location', 'southeast') ;
set(h,'fontsize',8) ;
grid on ;
axis square ;
vl_demo_print('kdtree_sift_distortion',.6) ;
% --------------------------------------------------------------------
function checkx(kdtree, X, t, n, mib, mab)
% --------------------------------------------------------------------
if nargin <= 4
mib = -inf * ones(size(X,1),1) ;
mab = +inf * ones(size(X,1),1) ;
end
lc = kdtree.trees(t).nodes.lowerChild(n) ;
uc = kdtree.trees(t).nodes.upperChild(n) ;
if lc < 0
for i=-lc:-uc-1
di = kdtree.trees(t).dataIndex(i) ;
if any(X(:,di) > mab)
error('a') ;
end
if any(X(:,di) < mib)
error('b') ;
end
end
return
end
i = kdtree.trees(t).nodes.splitDimension(n) ;
v = kdtree.trees(t).nodes.splitThreshold(n) ;
mab_ = mab ;
mab_(i) = min(mab(i), v) ;
checkx(kdtree, X, t, lc, mib, mab_) ;
mib_ = mib ;
mib_(i) = max(mib(i), v) ;
checkx(kdtree, X, t, uc, mib_, mab) ;
% --------------------------------------------------------------------
function kdtree = readflann(kdtree, path)
% --------------------------------------------------------------------
data = textread(path)' ;
for i=1:size(data,2)
nodeIds = data(1,:) ;
ni = find(nodeIds == data(1,i)) ;
if ~isnan(data(2,i))
% internal node
li = find(nodeIds == data(4,i)) ;
ri = find(nodeIds == data(5,i)) ;
kdtree.trees(1).nodes.lowerChild(ni) = int32(li) ;
kdtree.trees(1).nodes.upperChild(ni) = int32(ri) ;
kdtree.trees(1).nodes.splitThreshold(ni) = single(data(2,i)) ;
kdtree.trees(1).nodes.splitDimension(ni) = single(data(3,i)+1) ;
else
di = data(3,i) + 1 ;
kdtree.trees(1).nodes.lowerChild(ni) = int32(- di) ;
kdtree.trees(1).nodes.upperChild(ni) = int32(- di - 1) ;
end
kdtree.trees(1).dataIndex = uint32(1:kdtree.numData) ;
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_impattern.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/imop/vl_impattern.m
| 6,876 |
utf_8
|
1716a4d107f0186be3d11c647bc628ce
|
function im = vl_impattern(varargin)
% VL_IMPATTERN Generate an image from a stock pattern
% IM=VLPATTERN(NAME) returns an instance of the specified
% pattern. These stock patterns are useful for testing algoirthms.
%
% All generated patterns are returned as an image of class
% DOUBLE. Both gray-scale and colour images have range in [0,1].
%
% VL_IMPATTERN() without arguments shows a gallery of the stock
% patterns. The following patterns are supported:
%
% Wedge::
% The image of a wedge.
%
% Cone::
% The image of a cone.
%
% SmoothChecker::
% A checkerboard with Gaussian filtering on top. Use the
% option-value pair 'sigma', SIGMA to specify the standard
% deviation of the smoothing and the pair 'step', STEP to specfity
% the checker size in pixels.
%
% ThreeDotsSquare::
% A pattern with three small dots and two squares.
%
% UniformNoise::
% Random i.i.d. noise.
%
% Blobs:
% Gaussian blobs of various sizes and anisotropies.
%
% Blobs1:
% Gaussian blobs of various orientations and anisotropies.
%
% Blob:
% One Gaussian blob. Use the option-value pairs 'sigma',
% 'orientation', and 'anisotropy' to specify the respective
% parameters. 'sigma' is the scalar standard deviation of an
% isotropic blob (the image domain is the rectangle
% [-1,1]^2). 'orientation' is the clockwise rotation (as the Y
% axis points downards). 'anisotropy' (>= 1) is the ratio of the
% the largest over the smallest axis of the blob (the smallest
% axis length is set by 'sigma'). Set 'cut' to TRUE to cut half
% half of the blob.
%
% A stock image::
% Any of 'box', 'roofs1', 'roofs2', 'river1', 'river2', 'spotted'.
%
% All pattern accept a SIZE parameter [WIDTH,HEIGHT]. For all but
% the stock images, the default size is [128,128].
% Author: Andrea Vedaldi
% Copyright (C) 2012 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin > 0
pattern=varargin{1} ;
varargin=varargin(2:end) ;
else
pattern = 'gallery' ;
end
patterns = {'wedge','cone','smoothChecker','threeDotsSquare', ...
'blob', 'blobs', 'blobs1', ...
'box', 'roofs1', 'roofs2', 'river1', 'river2'} ;
% spooling
switch lower(pattern)
case 'wedge', im = wedge(varargin) ;
case 'cone', im = cone(varargin) ;
case 'smoothchecker', im = smoothChecker(varargin) ;
case 'threedotssquare', im = threeDotSquare(varargin) ;
case 'uniformnoise', im = uniformNoise(varargin) ;
case 'blob', im = blob(varargin) ;
case 'blobs', im = blobs(varargin) ;
case 'blobs1', im = blobs1(varargin) ;
case {'box','roofs1','roofs2','river1','river2','spots'}
im = stockImage(pattern, varargin) ;
case 'gallery'
clf ;
num = numel(patterns) ;
for p = 1:num
vl_tightsubplot(num,p,'box','outer') ;
imagesc(vl_impattern(patterns{p}),[0 1]) ;
axis image off ;
title(patterns{p}) ;
end
colormap gray ;
return ;
otherwise
error('Unknown patter ''%s''.', pattern) ;
end
if nargout == 0
clf ; imagesc(im) ; hold on ;
colormap gray ; axis image off ;
title(pattern) ;
clear im ;
end
function [u,v,opts,args] = commonOpts(args)
opts.size = [128 128] ;
[opts,args] = vl_argparse(opts, args) ;
ur = linspace(-1,1,opts.size(2)) ;
vr = linspace(-1,1,opts.size(1)) ;
[u,v] = meshgrid(ur,vr);
function im = wedge(args)
[u,v,opts,args] = commonOpts(args) ;
im = abs(u) + abs(v) > (1/4) ;
im(v < 0) = 0 ;
function im = cone(args)
[u,v,opts,args] = commonOpts(args) ;
im = sqrt(u.^2+v.^2) ;
im = im / max(im(:)) ;
function im = smoothChecker(args)
opts.size = [128 128] ;
opts.step = 16 ;
opts.sigma = 2 ;
opts = vl_argparse(opts, args) ;
[u,v] = meshgrid(0:opts.size(1)-1, 0:opts.size(2)-1) ;
im = xor((mod(u,opts.step*2) < opts.step),...
(mod(v,opts.step*2) < opts.step)) ;
im = double(im) ;
im = vl_imsmooth(im, opts.sigma) ;
function im = threeDotSquare(args)
[u,v,opts,args] = commonOpts(args) ;
im = ones(size(u)) ;
im(-2/3<u & u<2/3 & -2/3<v & v<2/3) = .75 ;
im(-1/3<u & u<1/3 & -1/3<v & v<1/3) = .50 ;
[drop,i] = min(abs(v(:,1))) ;
[drop,j1] = min(abs(u(1,:)-1/6)) ;
[drop,j2] = min(abs(u(1,:))) ;
[drop,j3] = min(abs(u(1,:)+1/6)) ;
im(i,j1) = 0 ;
im(i,j2) = 0 ;
im(i,j3) = 0 ;
function im = blobs(args)
[u,v,opts,args] = commonOpts(args) ;
im = zeros(size(u)) ;
num = 5 ;
square = 2 / num ;
sigma = square / 2 / 3 ;
scales = logspace(log10(0.5), log10(1), num) ;
skews = linspace(1,2,num) ;
for i=1:num
for j=1:num
cy = (i-1) * square + square/2 - 1;
cx = (j-1) * square + square/2 - 1;
A = sigma * diag([scales(i) scales(i)/skews(j)]) * [1 -1 ; 1 1] / sqrt(2) ;
C = inv(A'*A) ;
x = u - cx ;
y = v - cy ;
im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ;
end
end
im = im / max(im(:)) ;
function im = blob(args)
[u,v,opts,args] = commonOpts(args) ;
opts.sigma = 0.15 ;
opts.anisotropy = .5 ;
opts.orientation = 2/3 * pi ;
opts.cut = false ;
opts = vl_argparse(opts, args) ;
im = zeros(size(u)) ;
th = opts.orientation ;
R = [cos(th) -sin(th) ; sin(th) cos(th)] ;
A = opts.sigma * R * diag([opts.anisotropy 1]) ;
T = [0;0] ;
[x,y] = vl_waffine(inv(A),-inv(A)*T,u,v) ;
im = exp(-0.5 *(x.^2 + y.^2)) ;
if opts.cut
im = im .* double(x > 0) ;
end
function im = blobs1(args)
[u,v,opts,args] = commonOpts(args) ;
opts.number = 5 ;
opts.sigma = [] ;
opts = vl_argparse(opts, args) ;
im = zeros(size(u)) ;
square = 2 / opts.number ;
num = opts.number ;
if isempty(opts.sigma)
sigma = 1/6 * square ;
else
sigma = opts.sigma * square ;
end
rotations = linspace(0,pi,num+1) ;
rotations(end) = [] ;
skews = linspace(1,2,num) ;
for i=1:num
for j=1:num
cy = (i-1) * square + square/2 - 1;
cx = (j-1) * square + square/2 - 1;
th = rotations(i) ;
R = [cos(th) -sin(th); sin(th) cos(th)] ;
A = sigma * R * diag([1 1/skews(j)]) ;
C = inv(A*A') ;
x = u - cx ;
y = v - cy ;
im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ;
end
end
im = im / max(im(:)) ;
function im = uniformNoise(args)
opts.size = [128 128] ;
opts.seed = 1 ;
opts = vl_argparse(opts, args) ;
state = vl_twister('state') ;
vl_twister('state',opts.seed) ;
im = vl_twister(opts.size([2 1])) ;
vl_twister('state',state) ;
function im = stockImage(pattern,args)
opts.size = [] ;
opts = vl_argparse(opts, args) ;
switch pattern
case 'river1', path='river1.jpg' ;
case 'river2', path='river2.jpg' ;
case 'roofs1', path='roofs1.jpg' ;
case 'roofs2', path='roofs2.jpg' ;
case 'box', path='box.pgm' ;
case 'spots', path='spots.jpg' ;
end
im = imread(fullfile(vl_root,'data',path)) ;
im = im2double(im) ;
if ~isempty(opts.size)
im = imresize(im, opts.size) ;
im = max(im,0) ;
im = min(im,1) ;
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_tpsu.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/imop/vl_tpsu.m
| 1,755 |
utf_8
|
09f36e1a707c069b375eb2817d0e5f13
|
function [U,dU,delta]=vl_tpsu(X,Y)
% VL_TPSU Compute the U matrix of a thin-plate spline transformation
% U=VL_TPSU(X,Y) returns the matrix
%
% [ U(|X(:,1) - Y(:,1)|) ... U(|X(:,1) - Y(:,N)|) ]
% [ ]
% [ U(|X(:,M) - Y(:,1)|) ... U(|X(:,M) - Y(:,N)|) ]
%
% where X is a 2xM matrix and Y a 2xN matrix of points and U(r) is
% the opposite -r^2 log(r^2) of the radial basis function of the
% thin plate spline specified by X and Y.
%
% [U,dU]=vl_tpsu(x,y) returns the derivatives of the columns of U with
% respect to the parameters Y. The derivatives are arranged in a
% Mx2xN array, one layer per column of U.
%
% See also: VL_TPS(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if exist('tpsumx')
U = tpsumx(X,Y) ;
else
M=size(X,2) ;
N=size(Y,2) ;
% Faster than repmat, but still fairly slow
r2 = ...
(X( ones(N,1), :)' - Y( ones(1,M), :)).^2 + ...
(X( 1+ones(N,1), :)' - Y(1+ones(1,M), :)).^2 ;
U = - rb(r2) ;
end
if nargout > 1
M=size(X,2) ;
N=size(Y,2) ;
dx = X( ones(N,1), :)' - Y( ones(1,M), :) ;
dy = X(1+ones(N,1), :)' - Y(1+ones(1,M), :) ;
r2 = (dx.^2 + dy.^2) ;
r = sqrt(r2) ;
coeff = drb(r)./(r+eps) ;
dU = reshape( [coeff .* dx ; coeff .* dy], M, 2, N) ;
end
% The radial basis function
function y = rb(r2)
y = zeros(size(r2)) ;
sel = find(r2 ~= 0) ;
y(sel) = - r2(sel) .* log(r2(sel)) ;
% The derivative of the radial basis function
function y = drb(r)
y = zeros(size(r)) ;
sel = find(r ~= 0) ;
y(sel) = - 4 * r(sel) .* log(r(sel)) - 2 * r(sel) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_xyz2lab.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/imop/vl_xyz2lab.m
| 1,570 |
utf_8
|
09f95a6f9ae19c22486ec1157357f0e3
|
function J=vl_xyz2lab(I,il)
% VL_XYZ2LAB Convert XYZ color space to LAB
% J = VL_XYZ2LAB(I) converts the image from XYZ format to LAB format.
%
% VL_XYZ2LAB(I,IL) uses one of the illuminants A, B, C, E, D50, D55,
% D65, D75, D93. The default illuminatn is E.
%
% See also: VL_XYZ2LUV(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin < 2
il='E' ;
end
switch lower(il)
case 'a'
xw = 0.4476 ;
yw = 0.4074 ;
case 'b'
xw = 0.3324 ;
yw = 0.3474 ;
case 'c'
xw = 0.3101 ;
yw = 0.3162 ;
case 'e'
xw = 1/3 ;
yw = 1/3 ;
case 'd50'
xw = 0.3457 ;
yw = 0.3585 ;
case 'd55'
xw = 0.3324 ;
yw = 0.3474 ;
case 'd65'
xw = 0.312713 ;
yw = 0.329016 ;
case 'd75'
xw = 0.299 ;
yw = 0.3149 ;
case 'd93'
xw = 0.2848 ;
yw = 0.2932 ;
end
J=zeros(size(I)) ;
% Reference white
Yw = 1.0 ;
Xw = xw/yw ;
Zw = (1-xw-yw)/yw * Yw ;
% XYZ components
X = I(:,:,1) ;
Y = I(:,:,2) ;
Z = I(:,:,3) ;
x = X/Xw ;
y = Y/Yw ;
z = Z/Zw ;
L = 116 * f(y) - 16 ;
a = 500*(f(x) - f(y)) ;
b = 200*(f(y) - f(z)) ;
J = cat(3,L,a,b) ;
% --------------------------------------------------------------------
function b=f(a)
% --------------------------------------------------------------------
sp = find(a > 0.00856) ;
sm = find(a <= 0.00856) ;
k = 903.3 ;
b=zeros(size(a)) ;
b(sp) = a(sp).^(1/3) ;
b(sm) = (k*a(sm) + 16)/116 ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_gmm.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_gmm.m
| 1,332 |
utf_8
|
76782cae6c98781c6c38d4cbf5549d94
|
function results = vl_test_gmm(varargin)
% VL_TEST_GMM
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
vl_test_init ;
end
function s = setup()
randn('state',0) ;
s.X = randn(128, 1000) ;
end
function test_multithreading(s)
dataTypes = {'single','double'} ;
for dataType = dataTypes
conversion = str2func(char(dataType)) ;
X = conversion(s.X) ;
vl_twister('state',0) ;
vl_threads(0) ;
[means, covariances, priors, ll, posteriors] = ...
vl_gmm(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Initialization', 'rand') ;
vl_twister('state',0) ;
vl_threads(1) ;
[means_, covariances_, priors_, ll_, posteriors_] = ...
vl_gmm(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Initialization', 'rand') ;
vl_assert_almost_equal(means, means_, 1e-2) ;
vl_assert_almost_equal(covariances, covariances_, 1e-2) ;
vl_assert_almost_equal(priors, priors_, 1e-2) ;
vl_assert_almost_equal(ll, ll_, 1e-2 * abs(ll)) ;
vl_assert_almost_equal(posteriors, posteriors_, 1e-2) ;
end
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_twister.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_twister.m
| 1,251 |
utf_8
|
2bfb5a30cbd6df6ac80c66b73f8646da
|
function results = vl_test_twister(varargin)
% VL_TEST_TWISTER
vl_test_init ;
function test_illegal_args()
vl_assert_exception(@() vl_twister(-1), 'vl:invalidArgument') ;
vl_assert_exception(@() vl_twister(1, -1), 'vl:invalidArgument') ;
vl_assert_exception(@() vl_twister([1, -1]), 'vl:invalidArgument') ;
function test_seed_by_scalar()
rand('twister',1) ; a = rand ;
vl_twister('state',1) ; b = vl_twister ;
vl_assert_equal(a,b,'seed by scalar + VL_TWISTER()') ;
function test_get_set_state()
rand('twister',1) ; a = rand('twister') ;
vl_twister('state',1) ; b = vl_twister('state') ;
vl_assert_equal(a,b,'read state') ;
a(1) = a(1) + 1 ;
vl_twister('state',a) ; b = vl_twister('state') ;
vl_assert_equal(a,b,'set state') ;
function test_multi_dimensions()
b = rand('twister') ;
rand('twister',b) ;
vl_twister('state',b) ;
a=rand([1 2 3 4 5]) ;
b=vl_twister([1 2 3 4 5]) ;
vl_assert_equal(a,b,'VL_TWISTER([M N P ...])') ;
function test_multi_multi_args()
rand('twister',1) ; a=rand(1, 2, 3, 4, 5) ;
vl_twister('state',1) ; b=vl_twister(1, 2, 3, 4, 5) ;
vl_assert_equal(a,b,'VL_TWISTER(M, N, P, ...)') ;
function test_square()
rand('twister',1) ; a=rand(10) ;
vl_twister('state',1) ; b=vl_twister(10) ;
vl_assert_equal(a,b,'VL_TWISTER(N)') ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_kdtree.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_kdtree.m
| 2,449 |
utf_8
|
9d7ad2b435a88c22084b38e5eb5f9eb9
|
function results = vl_test_kdtree(varargin)
% VL_TEST_KDTREE
vl_test_init ;
function s = setup()
randn('state',0) ;
s.X = single(randn(10, 1000)) ;
s.Q = single(randn(10, 10)) ;
function test_nearest(s)
for tmethod = {'median', 'mean'}
for type = {@single, @double}
conv = type{1} ;
tmethod = char(tmethod) ;
X = conv(s.X) ;
Q = conv(s.Q) ;
tree = vl_kdtreebuild(X,'ThresholdMethod', tmethod) ;
[nn, d2] = vl_kdtreequery(tree, X, Q) ;
D2 = vl_alldist2(X, Q, 'l2') ;
[d2_, nn_] = min(D2) ;
vl_assert_equal(...
nn,uint32(nn_),...
'incorrect nns: type=%s th. method=%s', func2str(conv), tmethod) ;
vl_assert_almost_equal(...
d2,d2_,...
'incorrect distances: type=%s th. method=%s', func2str(conv), tmethod) ;
end
end
function test_nearests(s)
numNeighbors = 7 ;
tree = vl_kdtreebuild(s.X) ;
[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...
'numNeighbors', numNeighbors) ;
D2 = vl_alldist2(s.X, s.Q, 'l2') ;
[d2_, nn_] = sort(D2) ;
d2_ = d2_(1:numNeighbors, :) ;
nn_ = nn_(1:numNeighbors, :) ;
vl_assert_equal(nn,uint32(nn_)) ;
vl_assert_almost_equal(d2,d2_) ;
function test_ann(s)
vl_twister('state', 1) ;
numNeighbors = 7 ;
maxComparisons = numNeighbors * 50 ;
tree = vl_kdtreebuild(s.X) ;
[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...
'numNeighbors', numNeighbors, ...
'maxComparisons', maxComparisons) ;
D2 = vl_alldist2(s.X, s.Q, 'l2') ;
[d2_, nn_] = sort(D2) ;
d2_ = d2_(1:numNeighbors, :) ;
nn_ = nn_(1:numNeighbors, :) ;
for i=1:size(s.Q,2)
overlap = numel(intersect(nn(:,i), nn_(:,i))) / ...
numel(union(nn(:,i), nn_(:,i))) ;
assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ;
end
function test_ann_forest(s)
vl_twister('state', 1) ;
numNeighbors = 7 ;
maxComparisons = numNeighbors * 25 ;
numTrees = 5 ;
tree = vl_kdtreebuild(s.X, 'numTrees', 5) ;
[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...
'numNeighbors', numNeighbors, ...
'maxComparisons', maxComparisons) ;
D2 = vl_alldist2(s.X, s.Q, 'l2') ;
[d2_, nn_] = sort(D2) ;
d2_ = d2_(1:numNeighbors, :) ;
nn_ = nn_(1:numNeighbors, :) ;
for i=1:size(s.Q,2)
overlap = numel(intersect(nn(:,i), nn_(:,i))) / ...
numel(union(nn(:,i), nn_(:,i))) ;
assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ;
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_imwbackward.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_imwbackward.m
| 514 |
utf_8
|
33baa0784c8f6f785a2951d7f1b49199
|
function results = vl_test_imwbackward(varargin)
% VL_TEST_IMWBACKWARD
vl_test_init ;
function s = setup()
s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
function test_identity(s)
xr = 1:size(s.I,2) ;
yr = 1:size(s.I,1) ;
[x,y] = meshgrid(xr,yr) ;
vl_assert_almost_equal(s.I, vl_imwbackward(xr,yr,s.I,x,y)) ;
function test_invalid_args(s)
xr = 1:size(s.I,2) ;
yr = 1:size(s.I,1) ;
[x,y] = meshgrid(xr,yr) ;
vl_assert_exception(@() vl_imwbackward(xr,yr,single(s.I),x,y), 'vl:invalidArgument') ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_alphanum.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_alphanum.m
| 1,624 |
utf_8
|
2da2b768c2d0f86d699b8f31614aa424
|
function results = vl_test_alphanum(varargin)
% VL_TEST_ALPHANUM
vl_test_init ;
function s = setup()
s.strings = ...
{'1000X Radonius Maximus','10X Radonius','200X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','Allegia 50 Clasteron','Allegia 500 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 6R Clasteron','Alpha 100','Alpha 2','Alpha 200','Alpha 2A','Alpha 2A-8000','Alpha 2A-900','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 5000','Callisto Morphamax 600','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 700','Callisto Morphamax 7000','Xiph Xlater 10000','Xiph Xlater 2000','Xiph Xlater 300','Xiph Xlater 40','Xiph Xlater 5','Xiph Xlater 50','Xiph Xlater 500','Xiph Xlater 5000','Xiph Xlater 58'} ;
s.sortedStrings = ...
{'10X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','200X Radonius','1000X Radonius Maximus','Allegia 6R Clasteron','Allegia 50 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 500 Clasteron','Alpha 2','Alpha 2A','Alpha 2A-900','Alpha 2A-8000','Alpha 100','Alpha 200','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 600','Callisto Morphamax 700','Callisto Morphamax 5000','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 7000','Xiph Xlater 5','Xiph Xlater 40','Xiph Xlater 50','Xiph Xlater 58','Xiph Xlater 300','Xiph Xlater 500','Xiph Xlater 2000','Xiph Xlater 5000','Xiph Xlater 10000'} ;
function test_basic(s)
sorted = vl_alphanum(s.strings) ;
assert(isequal(sorted,s.sortedStrings)) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_printsize.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_printsize.m
| 1,447 |
utf_8
|
0f0b6437c648b7a2e1310900262bd765
|
function results = vl_test_printsize(varargin)
% VL_TEST_PRINTSIZE
vl_test_init ;
function s = setup()
s.fig = figure(1) ;
s.usletter = [8.5, 11] ; % inches
s.a4 = [8.26772, 11.6929] ;
clf(s.fig) ; plot(1:10) ;
function teardown(s)
close(s.fig) ;
function test_basic(s)
for sigma = [1 0.5 0.2]
vl_printsize(s.fig, sigma) ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(1), sigma*s.usletter(1), 1e-4) ;
vl_assert_almost_equal(pos(1), 0, 1e-4) ;
vl_assert_almost_equal(pos(3), sigma*s.usletter(1), 1e-4) ;
end
function test_papertype(s)
vl_printsize(s.fig, 1, 'papertype', 'a4') ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(1), s.a4(1), 1e-4) ;
function test_margin(s)
m = 0.5 ;
vl_printsize(s.fig, 1, 'margin', m) ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(1), s.usletter(1) * (1 + 2*m), 1e-4) ;
vl_assert_almost_equal(pos(1), s.usletter(1) * m, 1e-4) ;
function test_reference(s)
sigma = 1 ;
vl_printsize(s.fig, 1, 'reference', 'vertical') ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(2), sigma*s.usletter(2), 1e-4) ;
vl_assert_almost_equal(pos(2), 0, 1e-4) ;
vl_assert_almost_equal(pos(4), sigma*s.usletter(2), 1e-4) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_cummax.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_cummax.m
| 838 |
utf_8
|
5e98ee1681d4823f32ecc4feaa218611
|
function results = vl_test_cummax(varargin)
% VL_TEST_CUMMAX
vl_test_init ;
function test_basic()
vl_assert_almost_equal(...
vl_cummax(1), 1) ;
vl_assert_almost_equal(...
vl_cummax([1 2 3 4], 2), [1 2 3 4]) ;
function test_multidim()
a = [1 2 3 4 3 2 1] ;
b = [1 2 3 4 4 4 4] ;
for k=1:6
dims = ones(1,6) ;
dims(k) = numel(a) ;
a = reshape(a, dims) ;
b = reshape(b, dims) ;
vl_assert_almost_equal(...
vl_cummax(a, k), b) ;
end
function test_storage_classes()
types = {@double, @single, ...
@int32, @uint32, ...
@int16, @uint16, ...
@int8, @uint8} ;
if vl_matlabversion() > 71000
types = horzcat(types, {@int64, @uint64}) ;
end
for a = types
a = a{1} ;
for b = types
b = b{1} ;
vl_assert_almost_equal(...
vl_cummax(a(eye(3))), a(toeplitz([1 1 1], [1 0 0 ]))) ;
end
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_imintegral.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_imintegral.m
| 1,429 |
utf_8
|
4750f04ab0ac9fc4f55df2c8583e5498
|
function results = vl_test_imintegral(varargin)
% VL_TEST_IMINTEGRAL
vl_test_init ;
function state = setup()
state.I = ones(5,6) ;
state.correct = [ 1 2 3 4 5 6 ;
2 4 6 8 10 12 ;
3 6 9 12 15 18 ;
4 8 12 16 20 24 ;
5 10 15 20 25 30 ; ] ;
function test_matlab_equivalent(s)
vl_assert_equal(slow_imintegral(s.I), s.correct) ;
function test_basic(s)
vl_assert_equal(vl_imintegral(s.I), s.correct) ;
function test_multi_dimensional(s)
vl_assert_equal(vl_imintegral(repmat(s.I, [1 1 3])), ...
repmat(s.correct, [1 1 3])) ;
function test_random(s)
numTests = 50 ;
for i = 1:numTests
I = rand(5) ;
vl_assert_almost_equal(vl_imintegral(s.I), ...
slow_imintegral(s.I)) ;
end
function test_datatypes(s)
vl_assert_equal(single(vl_imintegral(s.I)), single(s.correct)) ;
vl_assert_equal(double(vl_imintegral(s.I)), double(s.correct)) ;
vl_assert_equal(uint32(vl_imintegral(s.I)), uint32(s.correct)) ;
vl_assert_equal(int32(vl_imintegral(s.I)), int32(s.correct)) ;
vl_assert_equal(int32(vl_imintegral(-s.I)), -int32(s.correct)) ;
function integral = slow_imintegral(I)
integral = zeros(size(I));
for k = 1:size(I,3)
for r = 1:size(I,1)
for c = 1:size(I,2)
integral(r,c,k) = sum(sum(I(1:r,1:c,k)));
end
end
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_sift.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_sift.m
| 1,318 |
utf_8
|
806c61f9db9f2ebb1d649c9bfcf3dc0a
|
function results = vl_test_sift(varargin)
% VL_TEST_SIFT
vl_test_init ;
function s = setup()
s.I = im2single(imread(fullfile(vl_root,'data','box.pgm'))) ;
[s.ubc.f, s.ubc.d] = ...
vl_ubcread(fullfile(vl_root,'data','box.sift')) ;
function test_ubc_descriptor(s)
err = [] ;
[f, d] = vl_sift(s.I,...
'firstoctave', -1, ...
'frames', s.ubc.f) ;
D2 = vl_alldist(f, s.ubc.f) ;
[drop, perm] = min(D2) ;
f = f(:,perm) ;
d = d(:,perm) ;
error = mean(sqrt(sum((single(s.ubc.d) - single(d)).^2))) ...
/ mean(sqrt(sum(single(s.ubc.d).^2))) ;
assert(error < 0.1, ...
'sift descriptor did not produce desctiptors similar to UBC ones') ;
function test_ubc_detector(s)
[f, d] = vl_sift(s.I,...
'firstoctave', -1, ...
'peakthresh', .01, ...
'edgethresh', 10) ;
s.ubc.f(4,:) = mod(s.ubc.f(4,:), 2*pi) ;
f(4,:) = mod(f(4,:), 2*pi) ;
% scale the components so that 1 pixel erro in x,y,z is equal to a
% 10-th of angle.
S = diag([1 1 1 20/pi]);
D2 = vl_alldist(S * s.ubc.f, S * f) ;
[d2,perm] = sort(min(D2)) ;
error = sqrt(d2) ;
quant80 = round(.8 * size(f,2)) ;
% check for less than one pixel error at 80% quantile
assert(error(quant80) < 1, ...
'sift detector did not produce enough keypoints similar to UBC ones') ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_binsum.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_binsum.m
| 1,377 |
utf_8
|
f07f0f29ba6afe0111c967ab0b353a9d
|
function results = vl_test_binsum(varargin)
% VL_TEST_BINSUM
vl_test_init ;
function test_three_args()
vl_assert_almost_equal(...
vl_binsum([0 0], 1, 2), [0 1]) ;
vl_assert_almost_equal(...
vl_binsum([1 7], -1, 1), [0 7]) ;
vl_assert_almost_equal(...
vl_binsum([1 7], -1, [1 2 2 2 2 2 2 2]), [0 0]) ;
function test_four_args()
vl_assert_almost_equal(...
vl_binsum(eye(3), [1 1 1], [1 2 3], 1), 2*eye(3)) ;
vl_assert_almost_equal(...
vl_binsum(eye(3), [1 1 1]', [1 2 3]', 2), 2*eye(3)) ;
vl_assert_almost_equal(...
vl_binsum(eye(3), 1, [1 2 3], 1), 2*eye(3)) ;
vl_assert_almost_equal(...
vl_binsum(eye(3), 1, [1 2 3]', 2), 2*eye(3)) ;
function test_3d_one()
Z = zeros(3,3,3) ;
B = 3*ones(3,1,3) ;
R = Z ; R(:,3,:) = 17 ;
vl_assert_almost_equal(...
vl_binsum(Z, 17, B, 2), R) ;
function test_3d_two()
Z = zeros(3,3,3) ;
B = 3*ones(3,3,1) ;
X = zeros(3,3,1) ; X(:,:,1) = 17 ;
R = Z ; R(:,:,3) = 17 ;
vl_assert_almost_equal(...
vl_binsum(Z, X, B, 3), R) ;
function test_storage_classes()
types = {@double, @single, ...
@int32, @uint32, ...
@int16, @uint16, ...
@int8, @uint8} ;
if vl_matlabversion() > 71000
types = horzcat(types, {@int64, @uint64}) ;
end
for a = types
a = a{1} ;
for b = types
b = b{1} ;
vl_assert_almost_equal(...
vl_binsum(a(eye(3)), a([1 1 1]), b([1 2 3]), 1), a(2*eye(3))) ;
end
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_lbp.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_lbp.m
| 892 |
utf_8
|
a79c0ce0c85e25c0b1657f3a0b499538
|
function results = vl_test_lbp(varargin)
% VL_TEST_TWISTER
vl_test_init ;
function test_unfiorm_lbps(s)
% enumerate the 56 uniform lbps
q = 0 ;
for i=0:7
for j=1:7
I = zeros(3) ;
p = mod(s.pixels - i + 8, 8) + 1 ;
I(p <= j) = 1 ;
f = vl_lbp(single(I), 3) ;
q = q + 1 ;
vl_assert_equal(find(f), q) ;
end
end
% constant lbps
I = [1 1 1 ; 1 0 1 ; 1 1 1] ;
f = vl_lbp(single(I), 3) ;
vl_assert_equal(find(f), 57) ;
I = [1 1 1 ; 1 1 1 ; 1 1 1] ;
f = vl_lbp(single(I), 3) ;
vl_assert_equal(find(f), 57) ;
% other lbps
I = [1 0 1 ; 0 0 0 ; 1 0 1] ;
f = vl_lbp(single(I), 3) ;
vl_assert_equal(find(f), 58) ;
function test_fliplr(s)
randn('state',0) ;
I = randn(256,256,1,'single') ;
f = vl_lbp(fliplr(I), 8) ;
f_ = vl_lbpfliplr(vl_lbp(I, 8)) ;
vl_assert_almost_equal(f,f_,1e-3) ;
function s = setup()
s.pixels = [5 6 7 ;
4 NaN 0 ;
3 2 1] ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_colsubset.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_colsubset.m
| 828 |
utf_8
|
be0c080007445b36333b863326fb0f15
|
function results = vl_test_colsubset(varargin)
% VL_TEST_COLSUBSET
vl_test_init ;
function s = setup()
s.x = [5 2 3 6 4 7 1 9 8 0] ;
function test_beginning(s)
vl_assert_equal(1:5, vl_colsubset(1:10, 5, 'beginning')) ;
vl_assert_equal(1:5, vl_colsubset(1:10, .5, 'beginning')) ;
function test_ending(s)
vl_assert_equal(6:10, vl_colsubset(1:10, 5, 'ending')) ;
vl_assert_equal(6:10, vl_colsubset(1:10, .5, 'ending')) ;
function test_largest(s)
vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, 5, 'largest')) ;
vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, .5, 'largest')) ;
function test_smallest(s)
vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, 5, 'smallest')) ;
vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, .5, 'smallest')) ;
function test_random(s)
assert(numel(intersect(s.x, vl_colsubset(s.x, 5, 'random'))) == 5) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_alldist.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_alldist.m
| 2,373 |
utf_8
|
9ea1a36c97fe715dfa2b8693876808ff
|
function results = vl_test_alldist(varargin)
% VL_TEST_ALLDIST
vl_test_init ;
function s = setup()
vl_twister('state', 0) ;
s.X = 3.1 * vl_twister(10,10) ;
s.Y = 4.7 * vl_twister(10,7) ;
function test_null_args(s)
vl_assert_equal(...
vl_alldist(zeros(15,12), zeros(15,0), 'kl2'), ...
zeros(12,0)) ;
vl_assert_equal(...
vl_alldist(zeros(15,0), zeros(15,0), 'kl2'), ...
zeros(0,0)) ;
vl_assert_equal(...
vl_alldist(zeros(15,0), zeros(15,12), 'kl2'), ...
zeros(0,12)) ;
vl_assert_equal(...
vl_alldist(zeros(0,15), zeros(0,12), 'kl2'), ...
zeros(15,12)) ;
function test_self(s)
vl_assert_almost_equal(...
vl_alldist(s.X, 'kl2'), ...
makedist(@(x,y) x*y, s.X, s.X), ...
1e-6) ;
function test_distances(s)
dists = {'chi2', 'l2', 'l1', 'hell', 'js', ...
'kchi2', 'kl2', 'kl1', 'khell', 'kjs'} ;
distsEquiv = { ...
@(x,y) (x-y)^2 / (x + y), ...
@(x,y) (x-y)^2, ...
@(x,y) abs(x-y), ...
@(x,y) (sqrt(x) - sqrt(y))^2, ...
@(x,y) x - x .* log2(1 + y/x) + y - y .* log2(1 + x/y), ...
@(x,y) 2 * (x*y) / (x + y), ...
@(x,y) x*y, ...
@(x,y) min(x,y), ...
@(x,y) sqrt(x.*y), ...
@(x,y) .5 * (x .* log2(1 + y/x) + y .* log2(1 + x/y))} ;
types = {'single', 'double'} ;
for simd = [0 1]
for d = 1:length(dists)
for t = 1:length(types)
vl_simdctrl(simd) ;
X = feval(str2func(types{t}), s.X) ;
Y = feval(str2func(types{t}), s.Y) ;
vl_assert_almost_equal(...
vl_alldist(X,Y,dists{d}), ...
makedist(distsEquiv{d},X,Y), ...
1e-4, ...
'alldist failed for dist=%s type=%s simd=%d', ...
dists{d}, ...
types{t}, ...
simd) ;
end
end
end
function test_distance_kernel_pairs(s)
dists = {'chi2', 'l2', 'l1', 'hell', 'js'} ;
for d = 1:length(dists)
dist = char(dists{d}) ;
X = s.X ;
Y = s.Y ;
ker = ['k' dist] ;
kxx = vl_alldist(X,X,ker) ;
kyy = vl_alldist(Y,Y,ker) ;
kxy = vl_alldist(X,Y,ker) ;
kxx = repmat(diag(kxx), 1, size(s.Y,2)) ;
kyy = repmat(diag(kyy), 1, size(s.X,1))' ;
d2 = vl_alldist(X,Y,dist) ;
vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ;
end
function D = makedist(cmp,X,Y)
[d,m] = size(X) ;
[d,n] = size(Y) ;
D = zeros(m,n) ;
for i = 1:m
for j = 1:n
acc = 0 ;
for k = 1:d
acc = acc + cmp(X(k,i),Y(k,j)) ;
end
D(i,j) = acc ;
end
end
conv = str2func(class(X)) ;
D = conv(D) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_ihashsum.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_ihashsum.m
| 581 |
utf_8
|
edc283062469af62056b0782b171f5fc
|
function results = vl_test_ihashsum(varargin)
% VL_TEST_IHASHSUM
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(round(16*rand(2,100))) ;
sel = find(all(s.data==0)) ;
s.data(1,sel)=1 ;
function test_hash(s)
D = size(s.data,1) ;
K = 5 ;
h = zeros(1,K,'uint32') ;
id = zeros(D,K,'uint8');
next = zeros(1,K,'uint32') ;
[h,id,next] = vl_ihashsum(h,id,next,K,s.data) ;
sel = vl_ihashfind(id,next,K,s.data) ;
count = double(h(sel)) ;
[drop,i,j] = unique(s.data','rows') ;
for k=1:size(s.data,2)
count_(k) = sum(j == j(k)) ;
end
vl_assert_equal(count,count_) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_grad.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_grad.m
| 434 |
utf_8
|
4d03eb33a6a4f68659f868da95930ffb
|
function results = vl_test_grad(varargin)
% VL_TEST_GRAD
vl_test_init ;
function s = setup()
s.I = rand(150,253) ;
s.I_small = rand(2,2) ;
function test_equiv(s)
vl_assert_equal(gradient(s.I), vl_grad(s.I)) ;
function test_equiv_small(s)
vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;
function test_equiv_forward(s)
Ix = diff(s.I,2,1) ;
Iy = diff(s.I,2,1) ;
vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_whistc.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_whistc.m
| 1,384 |
utf_8
|
81c446d35c82957659840ab2a579ec2c
|
function results = vl_test_whistc(varargin)
% VL_TEST_WHISTC
vl_test_init ;
function test_acc()
x = ones(1, 10) ;
e = 1 ;
o = 1:10 ;
vl_assert_equal(vl_whistc(x, o, e), 55) ;
function test_basic()
x = 1:10 ;
e = 1:10 ;
o = ones(1, 10) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
x = linspace(-1,11,100) ;
o = ones(size(x)) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
function test_multidim()
x = rand(10, 20, 30) ;
e = linspace(0,1,10) ;
o = ones(size(x)) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ;
vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ;
vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ;
function test_nan()
x = rand(10, 20, 30) ;
e = linspace(0,1,10) ;
o = ones(size(x)) ;
x(1:7:end) = NaN ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ;
vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ;
vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ;
function test_no_edges()
x = rand(10, 20, 30) ;
o = ones(size(x)) ;
vl_assert_equal(histc(1, []), vl_whistc(1, 1, [])) ;
vl_assert_equal(histc(x, []), vl_whistc(x, o, [])) ;
vl_assert_equal(histc(x, [], 1), vl_whistc(x, o, [], 1)) ;
vl_assert_equal(histc(x, [], 2), vl_whistc(x, o, [], 2)) ;
vl_assert_equal(histc(x, [], 3), vl_whistc(x, o, [], 3)) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_roc.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_roc.m
| 1,019 |
utf_8
|
9b2ae71c9dc3eda0fc54c65d55054d0c
|
function results = vl_test_roc(varargin)
% VL_TEST_ROC
vl_test_init ;
function s = setup()
s.scores0 = [5 4 3 2 1] ;
s.scores1 = [5 3 4 2 1] ;
s.labels = [1 1 -1 -1 -1] ;
function test_perfect_tptn(s)
[tpr,tnr] = vl_roc(s.labels,s.scores0) ;
vl_assert_almost_equal(tpr, [0 1 2 2 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 3 3 2 1 0] / 3) ;
function test_perfect_metrics(s)
[tpr,tnr,info] = vl_roc(s.labels,s.scores0) ;
vl_assert_almost_equal(info.eer, 0) ;
vl_assert_almost_equal(info.auc, 1) ;
function test_swap1_tptn(s)
[tpr,tnr] = vl_roc(s.labels,s.scores1) ;
vl_assert_almost_equal(tpr, [0 1 1 2 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 3 2 2 1 0] / 3) ;
function test_swap1_tptn_stable(s)
[tpr,tnr] = vl_roc(s.labels,s.scores1,'stable',true) ;
vl_assert_almost_equal(tpr, [1 2 1 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 2 2 1 0] / 3) ;
function test_swap1_metrics(s)
[tpr,tnr,info] = vl_roc(s.labels,s.scores1) ;
vl_assert_almost_equal(info.eer, 1/3) ;
vl_assert_almost_equal(info.auc, 1 - 1/(2*3)) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_dsift.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_dsift.m
| 2,048 |
utf_8
|
fbbfb16d5a21936c1862d9551f657ccc
|
function results = vl_test_dsift(varargin)
% VL_TEST_DSIFT
vl_test_init ;
function s = setup()
I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
s.I = rgb2gray(single(I)) ;
function test_fast_slow(s)
binSize = 4 ; % bin size in pixels
magnif = 3 ; % bin size / keypoint scale
scale = binSize / magnif ;
windowSize = 5 ;
[f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...
'size', binSize, ...
'step', 10, ...
'bounds', [20,20,210,140], ...
'windowsize', windowSize, ...
'floatdescriptors') ;
[f_, d_] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...
'size', binSize, ...
'step', 10, ...
'bounds', [20,20,210,140], ...
'windowsize', windowSize, ...
'floatdescriptors', ...
'fast') ;
error = std(d_(:) - d(:)) / std(d(:)) ;
assert(error < 0.1, 'dsift fast approximation not close') ;
function test_sift(s)
binSize = 4 ; % bin size in pixels
magnif = 3 ; % bin size / keypoint scale
scale = binSize / magnif ;
windowSizeRange = [1 1.2 5] ;
for wi = 1:length(windowSizeRange)
windowSize = windowSizeRange(wi) ;
[f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...
'size', binSize, ...
'step', 10, ...
'bounds', [20,20,210,140], ...
'windowsize', windowSize, ...
'floatdescriptors') ;
numKeys = size(f, 2) ;
f_ = [f ; ones(1, numKeys) * scale ; zeros(1, numKeys)] ;
[f_, d_] = vl_sift(s.I, ...
'magnif', magnif, ...
'frames', f_, ...
'firstoctave', -1, ...
'levels', 5, ...
'floatdescriptors', ...
'windowsize', windowSize) ;
error = std(d_(:) - d(:)) / std(d(:)) ;
assert(error < 0.1, 'dsift and sift equivalence') ;
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_alldist2.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_alldist2.m
| 2,284 |
utf_8
|
89a787e3d83516653ae8d99c808b9d67
|
function results = vl_test_alldist2(varargin)
% VL_TEST_ALLDIST
vl_test_init ;
% TODO: test integer classes
function s = setup()
vl_twister('state', 0) ;
s.X = 3.1 * vl_twister(10,10) ;
s.Y = 4.7 * vl_twister(10,7) ;
function test_null_args(s)
vl_assert_equal(...
vl_alldist2(zeros(15,12), zeros(15,0), 'kl2'), ...
zeros(12,0)) ;
vl_assert_equal(...
vl_alldist2(zeros(15,0), zeros(15,0), 'kl2'), ...
zeros(0,0)) ;
vl_assert_equal(...
vl_alldist2(zeros(15,0), zeros(15,12), 'kl2'), ...
zeros(0,12)) ;
vl_assert_equal(...
vl_alldist2(zeros(0,15), zeros(0,12), 'kl2'), ...
zeros(15,12)) ;
function test_self(s)
vl_assert_almost_equal(...
vl_alldist2(s.X, 'kl2'), ...
makedist(@(x,y) x*y, s.X, s.X), ...
1e-6) ;
function test_distances(s)
dists = {'chi2', 'l2', 'l1', 'hell', ...
'kchi2', 'kl2', 'kl1', 'khell'} ;
distsEquiv = { ...
@(x,y) (x-y)^2 / (x + y), ...
@(x,y) (x-y)^2, ...
@(x,y) abs(x-y), ...
@(x,y) (sqrt(x) - sqrt(y))^2, ...
@(x,y) 2 * (x*y) / (x + y), ...
@(x,y) x*y, ...
@(x,y) min(x,y), ...
@(x,y) sqrt(x.*y)};
types = {'single', 'double', 'sparse'} ;
for simd = [0 1]
for d = 1:length(dists)
for t = 1:length(types)
vl_simdctrl(simd) ;
X = feval(str2func(types{t}), s.X) ;
Y = feval(str2func(types{t}), s.Y) ;
a = vl_alldist2(X,Y,dists{d}) ;
b = makedist(distsEquiv{d},X,Y) ;
vl_assert_almost_equal(a,b, ...
1e-4, ...
'alldist failed for dist=%s type=%s simd=%d', ...
dists{d}, ...
types{t}, ...
simd) ;
end
end
end
function test_distance_kernel_pairs(s)
dists = {'chi2', 'l2', 'l1', 'hell'} ;
for d = 1:length(dists)
dist = char(dists{d}) ;
X = s.X ;
Y = s.Y ;
ker = ['k' dist] ;
kxx = vl_alldist2(X,X,ker) ;
kyy = vl_alldist2(Y,Y,ker) ;
kxy = vl_alldist2(X,Y,ker) ;
kxx = repmat(diag(kxx), 1, size(s.Y,2)) ;
kyy = repmat(diag(kyy), 1, size(s.X,1))' ;
d2 = vl_alldist2(X,Y,dist) ;
vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ;
end
function D = makedist(cmp,X,Y)
[d,m] = size(X) ;
[d,n] = size(Y) ;
D = zeros(m,n) ;
for i = 1:m
for j = 1:n
acc = 0 ;
for k = 1:d
acc = acc + cmp(X(k,i),Y(k,j)) ;
end
D(i,j) = acc ;
end
end
conv = str2func(class(X)) ;
D = conv(D) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_fisher.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_fisher.m
| 2,097 |
utf_8
|
c9afd9ab635bd412cbf8be3c2d235f6b
|
function results = vl_test_fisher(varargin)
% VL_TEST_FISHER
vl_test_init ;
function s = setup()
randn('state',0) ;
dimension = 5 ;
numData = 21 ;
numComponents = 3 ;
s.x = randn(dimension,numData) ;
s.mu = randn(dimension,numComponents) ;
s.sigma2 = ones(dimension,numComponents) ;
s.prior = ones(1,numComponents) ;
s.prior = s.prior / sum(s.prior) ;
function test_basic(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior) ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_norm(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'normalized') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_sqrt(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'squareroot') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_improved(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_fast(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior, true) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved', 'fast') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function enc = simple_fisher(x, mu, sigma2, pri, fast)
if nargin < 5, fast = false ; end
sigma = sqrt(sigma2) ;
for k = 1:size(mu,2)
delta{k} = bsxfun(@times, bsxfun(@minus, x, mu(:,k)), 1./sigma(:,k)) ;
q(k,:) = log(pri(k)) - 0.5 * sum(log(sigma2(:,k))) - 0.5 * sum(delta{k}.^2,1) ;
end
q = exp(bsxfun(@minus, q, max(q,[],1))) ;
q = bsxfun(@times, q, 1 ./ sum(q,1)) ;
n = size(x,2) ;
if fast
[~,i] = max(q) ;
q = zeros(size(q)) ;
q(sub2ind(size(q),i,1:n)) = 1 ;
end
for k = 1:size(mu,2)
u{k} = delta{k} * q(k,:)' / n / sqrt(pri(k)) ;
v{k} = (delta{k}.^2 - 1) * q(k,:)' / n / sqrt(2*pri(k)) ;
end
enc = cat(1, u{:}, v{:}) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_imsmooth.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_imsmooth.m
| 1,837 |
utf_8
|
718235242cad61c9804ba5e881c22f59
|
function results = vl_test_imsmooth(varargin)
% VL_TEST_IMSMOOTH
vl_test_init ;
function s = setup()
I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
I = max(min(vl_imdown(I),1),0) ;
s.I = single(I) ;
function test_pad_by_continuity(s)
% Convolving a constant signal padded with continuity does not change
% the signal.
I = ones(3) ;
for ker = {'triangular', 'gaussian'}
ker = char(ker) ;
J = vl_imsmooth(I, 2, ...
'kernel', ker, ...
'padding', 'continuity') ;
vl_assert_almost_equal(J, I, 1e-4, ...
'padding by continutiy with kernel = %s', ker) ;
end
function test_kernels(s)
for ker = {'triangular', 'gaussian'}
ker = char(ker) ;
for type = {@single, @double}
for simd = [0 1]
for sigma = [1 2 7]
for step = [1 2 3]
vl_simdctrl(simd) ;
conv = type{1} ;
g = equivalent_kernel(ker, sigma) ;
J = vl_imsmooth(conv(s.I), sigma, ...
'kernel', ker, ...
'padding', 'zero', ...
'subsample', step) ;
J_ = conv(convolve(s.I, g, step)) ;
vl_assert_almost_equal(J, J_, 1e-4, ...
'kernel=%s sigma=%f step=%d simd=%d', ...
ker, sigma, step, simd) ;
end
end
end
end
end
function g = equivalent_kernel(ker, sigma)
switch ker
case 'gaussian'
W = ceil(4*sigma) ;
g = exp(-.5*((-W:W)/(sigma+eps)).^2) ;
case 'triangular'
W = max(round(sigma),1) ;
g = W - abs(-W+1:W-1) ;
end
g = g / sum(g) ;
function I = convolve(I, g, step)
if strcmp(class(I),'single')
g = single(g) ;
else
g = double(g) ;
end
for k=1:size(I,3)
I(:,:,k) = conv2(g,g,I(:,:,k),'same');
end
I = I(1:step:end,1:step:end,:) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_svmtrain.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_svmtrain.m
| 4,277 |
utf_8
|
071b7c66191a22e8236fda16752b27aa
|
function results = vl_test_svmtrain(varargin)
% VL_TEST_SVMTRAIN
vl_test_init ;
end
function s = setup()
randn('state',0) ;
Np = 10 ;
Nn = 10 ;
xp = diag([1 3])*randn(2, Np) ;
xn = diag([1 3])*randn(2, Nn) ;
xp(1,:) = xp(1,:) + 2 + 1 ;
xn(1,:) = xn(1,:) - 2 + 1 ;
s.x = [xp xn] ;
s.y = [ones(1,Np) -ones(1,Nn)] ;
s.lambda = 0.01 ;
s.biasMultiplier = 10 ;
if 0
figure(1) ; clf;
vl_plotframe(xp, 'g') ; hold on ;
vl_plotframe(xn, 'r') ;
axis equal ; grid on ;
end
% Run LibSVM as an accuate solver to compare results with. Note that
% LibSVM optimizes a slightly different cost function due to the way
% the bias is handled.
% [s.w, s.b] = accurate_solver(s.x, s.y, s.lambda, s.biasMultiplier) ;
s.w = [1.180762951236242; 0.098366470721632] ;
s.b = -1.540018443946204 ;
s.obj = obj(s, s.w, s.b) ;
end
function test_sgd_basic(s)
for conv = {@single, @double}
conv = conv{1} ;
vl_twister('state',0) ;
[w b info] = vl_svmtrain(s.x, s.y, s.lambda, ...
'Solver', 'sgd', ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', 1/s.biasMultiplier, ...
'MaxNumIterations', 1e5, ...
'Epsilon', 1e-3) ;
% there are no absolute guarantees on the objective gap, but
% the heuristic SGD uses as stopping criterion seems reasonable
% within a factor 10 at least.
o = obj(s, w, b) ;
gap = o - s.obj ;
vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ;
assert(gap <= 1e-2) ;
end
end
function test_sdca_basic(s)
for conv = {@single, @double}
conv = conv{1} ;
vl_twister('state',0) ;
[w b info] = vl_svmtrain(s.x, s.y, s.lambda, ...
'Solver', 'sdca', ...
'BiasMultiplier', s.biasMultiplier, ...
'MaxNumIterations', 1e5, ...
'Epsilon', 1e-3) ;
% the gap with the accurate solver cannot be
% greater than the duality gap.
o = obj(s, w, b) ;
gap = o - s.obj ;
vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ;
assert(gap <= 1e-3) ;
end
end
function test_weights(s)
for algo = {'sgd', 'sdca'}
for conv = {@single, @double}
conv = conv{1} ;
vl_twister('state',0) ;
numRepeats = 10 ;
pos = find(s.y > 0) ;
neg = find(s.y < 0) ;
weights = ones(1, numel(s.y)) ;
weights(pos) = numRepeats ;
% simulate weighting by repeating positives
[w b info] = vl_svmtrain(...
s.x(:, [repmat(pos,1,numRepeats) neg]), ...
s.y(:, [repmat(pos,1,numRepeats) neg]), ...
s.lambda / (numel(pos) *numRepeats + numel(neg)) / (numel(pos) + numel(neg)), ...
'Solver', 'sdca', ...
'BiasMultiplier', s.biasMultiplier, ...
'MaxNumIterations', 1e6, ...
'Epsilon', 1e-4) ;
% apply weigthing
[w_ b_ info_] = vl_svmtrain(...
s.x, ...
s.y, ...
s.lambda, ...
'Solver', char(algo), ...
'BiasMultiplier', s.biasMultiplier, ...
'MaxNumIterations', 1e6, ...
'Epsilon', 1e-4, ...
'Weights', weights) ;
vl_assert_almost_equal(conv([w; b]), conv([w_; b_]), 0.05) ;
end
end
end
function test_homkermap(s)
for solver = {'sgd', 'sdca'}
for conv = {@single,@double}
conv = conv{1} ;
dataset = vl_svmdataset(conv(s.x), 'homkermap', struct('order',1)) ;
vl_twister('state',0) ;
[w_ b_] = vl_svmtrain(dataset, s.y, s.lambda) ;
x_hom = vl_homkermap(conv(s.x), 1) ;
vl_twister('state',0) ;
[w b] = vl_svmtrain(x_hom, s.y, s.lambda) ;
vl_assert_almost_equal([w; b],[w_; b_], 1e-7) ;
end
end
end
function [w,b] = accurate_solver(X, y, lambda, biasMultiplier)
addpath opt/libsvm/matlab/
N = size(X,2) ;
model = svmtrain(y', [(1:N)' X'*X], sprintf(' -c %f -t 4 -e 0.00001 ', 1/(lambda*N))) ;
w = X(:,model.SVs) * model.sv_coef ;
b = - model.rho ;
format long ;
disp('model w:')
disp(w)
disp('bias b:')
disp(b)
end
function o = obj(s, w, b)
o = (sum(w.*w) + b*b) * s.lambda / 2 + mean(max(0, 1 - s.y .* (w'*s.x + b))) ;
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_phow.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_phow.m
| 549 |
utf_8
|
f761a3bb218af855986263c67b2da411
|
function results = vl_test_phow(varargin)
% VL_TEST_PHOPW
vl_test_init ;
function s = setup()
s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
s.I = single(s.I) ;
function test_gray(s)
[f,d] = vl_phow(s.I, 'color', 'gray') ;
assert(size(d,1) == 128) ;
function test_rgb(s)
[f,d] = vl_phow(s.I, 'color', 'rgb') ;
assert(size(d,1) == 128*3) ;
function test_hsv(s)
[f,d] = vl_phow(s.I, 'color', 'hsv') ;
assert(size(d,1) == 128*3) ;
function test_opponent(s)
[f,d] = vl_phow(s.I, 'color', 'opponent') ;
assert(size(d,1) == 128*3) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_kmeans.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_kmeans.m
| 3,632 |
utf_8
|
0e1d6f4f8101c8982a0e743e0980c65a
|
function results = vl_test_kmeans(varargin)
% VL_TEST_KMEANS
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
vl_test_init ;
function s = setup()
randn('state',0) ;
s.X = randn(128, 100) ;
function test_basic(s)
[centers, assignments, en] = vl_kmeans(s.X, 10, 'NumRepetitions', 10) ;
[centers_, assignments_, en_] = simpleKMeans(s.X, 10) ;
assert(en_ <= 1.1 * en, 'vl_kmeans did not optimize enough') ;
function test_algorithms(s)
distances = {'l1', 'l2'} ;
dataTypes = {'single','double'} ;
for dataType = dataTypes
for distance = distances
distance = char(distance) ;
conversion = str2func(char(dataType)) ;
X = conversion(s.X) ;
vl_twister('state',0) ;
[centers, assignments, en] = vl_kmeans(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Algorithm', 'Lloyd', ...
'Distance', distance) ;
vl_twister('state',0) ;
[centers_, assignments_, en_] = vl_kmeans(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Algorithm', 'Elkan', ...
'Distance', distance) ;
vl_twister('state',0) ;
[centers__, assignments__, en__] = vl_kmeans(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Algorithm', 'ANN', ...
'Distance', distance, ...
'NumTrees', 3, ...
'MaxNumComparisons',0) ;
vl_assert_almost_equal(centers, centers_, 1e-5) ;
vl_assert_almost_equal(assignments, assignments_, 1e-5) ;
vl_assert_almost_equal(en, en_, 1e-4) ;
vl_assert_almost_equal(centers, centers__, 1e-5) ;
vl_assert_almost_equal(assignments, assignments__, 1e-5) ;
vl_assert_almost_equal(en, en__, 1e-4) ;
vl_assert_almost_equal(centers_, centers__, 1e-5) ;
vl_assert_almost_equal(assignments_, assignments__, 1e-5) ;
vl_assert_almost_equal(en_, en__, 1e-4) ;
end
end
function test_patterns(s)
distances = {'l1', 'l2'} ;
dataTypes = {'single','double'} ;
for dataType = dataTypes
for distance = distances
distance = char(distance) ;
conversion = str2func(char(dataType)) ;
data = [1 1 0 0 ;
1 0 1 0] ;
data = conversion(data) ;
[centers, assignments, en] = vl_kmeans(data, 4, ...
'NumRepetitions', 100, ...
'Distance', distance) ;
assert(isempty(setdiff(data', centers', 'rows'))) ;
end
end
function [centers, assignments, en] = simpleKMeans(X, numCenters)
[dimension, numData] = size(X) ;
centers = randn(dimension, numCenters) ;
for iter = 1:10
[dists, assignments] = min(vl_alldist(centers, X)) ;
en = sum(dists) ;
centers = [zeros(dimension, numCenters) ; ones(1, numCenters)] ;
centers = vl_binsum(centers, ...
[X ; ones(1,numData)], ...
repmat(assignments, dimension+1, 1), 2) ;
centers = centers(1:end-1, :) ./ repmat(centers(end,:), dimension, 1) ;
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_hikmeans.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_hikmeans.m
| 463 |
utf_8
|
dc3b493646e66316184e86ff4e6138ab
|
function results = vl_test_hikmeans(varargin)
% VL_TEST_IKMEANS
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(rand(2,1000) * 255) ;
function test_basic(s)
[tree, assign] = vl_hikmeans(s.data,3,100) ;
assign_ = vl_hikmeanspush(tree, s.data) ;
vl_assert_equal(assign,assign_) ;
function test_elkan(s)
[tree, assign] = vl_hikmeans(s.data,3,100,'method','elkan') ;
assign_ = vl_hikmeanspush(tree, s.data) ;
vl_assert_equal(assign,assign_) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_aib.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_aib.m
| 1,277 |
utf_8
|
78978ae54e7ebe991d136336ba4bf9c6
|
function results = vl_test_aib(varargin)
% VL_TEST_AIB
vl_test_init ;
function s = setup()
s = [] ;
function test_basic(s)
Pcx = [.3 .3 0 0
0 0 .2 .2] ;
% This results in the AIB tree
%
% 1 - \
% 5 - \
% 2 - / \
% - 7
% 3 - \ /
% 6 - /
% 4 - /
%
% coded by the map [5 5 6 6 7 1] (1 denotes the root).
[parents,cost] = vl_aib(Pcx) ;
vl_assert_equal(parents, [5 5 6 6 7 7 1]) ;
vl_assert_almost_equal(mi(Pcx)*[1 1 1], cost(1:3), 1e-3) ;
[cut,map,short] = vl_aibcut(parents,2) ;
vl_assert_equal(cut, [5 6]) ;
vl_assert_equal(map, [1 1 2 2 1 2 0]) ;
vl_assert_equal(short, [5 5 6 6 5 6 7]) ;
function test_cluster_null(s)
Pcx = [.5 .5 0 0
0 0 0 0] ;
% This results in the AIB tree
%
% 1 - \
% 5
% 2 - /
%
% 3 x
%
% 4 x
%
% If ClusterNull is specified, the values 3 and 4
% which have zero probability are merged first
%
% 1 ----------\
% 7
% 2 ----- \ /
% 6-/
% 3 -\ /
% 5 -/
% 4 -/
parents1 = vl_aib(Pcx) ;
parents2 = vl_aib(Pcx,'ClusterNull') ;
vl_assert_equal(parents1, [5 5 0 0 1 0 0]) ;
vl_assert_equal(parents2(3), parents2(4)) ;
function x = mi(P)
% mutual information
P1 = sum(P,1) ;
P2 = sum(P,2) ;
x = sum(sum(P .* log(max(P,1e-10) ./ (P2*P1)))) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_plotbox.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_plotbox.m
| 414 |
utf_8
|
aa06ce4932a213fb933bbede6072b029
|
function results = vl_test_plotbox(varargin)
% VL_TEST_PLOTBOX
vl_test_init ;
function test_basic(s)
figure(1) ; clf ;
vl_plotbox([-1 -1 1 1]') ;
xlim([-2 2]) ;
ylim([-2 2]) ;
close(1) ;
function test_multiple(s)
figure(1) ; clf ;
randn('state', 0) ;
vl_plotbox(randn(4,10)) ;
close(1) ;
function test_style(s)
figure(1) ; clf ;
randn('state', 0) ;
vl_plotbox(randn(4,10), 'r-.', 'LineWidth', 3) ;
close(1) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_imarray.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_imarray.m
| 795 |
utf_8
|
c5e6a5aa8c2e63e248814f5bd89832a8
|
function results = vl_test_imarray(varargin)
% VL_TEST_IMARRAY
vl_test_init ;
function test_movie_rgb(s)
A = rand(23,15,3,4) ;
B = vl_imarray(A,'movie',true) ;
function test_movie_indexed(s)
cmap = get(0,'DefaultFigureColormap') ;
A = uint8(size(cmap,1)*rand(23,15,4)) ;
A = min(A,size(cmap,1)-1) ;
B = vl_imarray(A,'movie',true) ;
function test_movie_gray_indexed(s)
A = uint8(255*rand(23,15,4)) ;
B = vl_imarray(A,'movie',true,'cmap',gray(256)) ;
for k=1:size(A,3)
vl_assert_equal(squeeze(A(:,:,k)), ...
frame2im(B(k))) ;
end
function test_basic(s)
M = 3 ;
N = 4 ;
width = 32 ;
height = 15 ;
for i=1:M
for j=1:N
A{i,j} = rand(width,height) ;
end
end
A1 = A';
A1 = cat(3,A1{:}) ;
A2 = cell2mat(A) ;
B = vl_imarray(A1, 'layout', [M N]) ;
vl_assert_equal(A2,B) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_homkermap.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_homkermap.m
| 1,903 |
utf_8
|
c157052bf4213793a961bde1f73fb307
|
function results = vl_test_homkermap(varargin)
% VL_TEST_HOMKERMAP
vl_test_init ;
function check_ker(ker, n, window, period)
args = {n, ker, 'window', window} ;
if nargin > 3
args = {args{:}, 'period', period} ;
end
x = [-1 -.5 0 .5 1] ;
y = linspace(0,2,100) ;
for conv = {@single, @double}
x = feval(conv{1}, x) ;
y = feval(conv{1}, y) ;
sx = sign(x) ;
sy = sign(y) ;
psix = vl_homkermap(x, args{:}) ;
psiy = vl_homkermap(y, args{:}) ;
k = vl_alldist(psix,psiy,'kl2') ;
k_ = (sx'*sy) .* vl_alldist(sx.*x,sy.*y,ker) ;
vl_assert_almost_equal(k, k_, 2e-2) ;
end
function test_uniform_kchi2(), check_ker('kchi2', 3, 'uniform', 15) ;
function test_uniform_kjs(), check_ker('kjs', 3, 'uniform', 15) ;
function test_uniform_kl1(), check_ker('kl1', 29, 'uniform', 15) ;
function test_rect_kchi2(), check_ker('kchi2', 3, 'rectangular', 15) ;
function test_rect_kjs(), check_ker('kjs', 3, 'rectangular', 15) ;
function test_rect_kl1(), check_ker('kl1', 29, 'rectangular', 10) ;
function test_auto_uniform_kchi2(),check_ker('kchi2', 3, 'uniform') ;
function test_auto_uniform_kjs(), check_ker('kjs', 3, 'uniform') ;
function test_auto_uniform_kl1(), check_ker('kl1', 25, 'uniform') ;
function test_auto_rect_kchi2(), check_ker('kchi2', 3, 'rectangular') ;
function test_auto_rect_kjs(), check_ker('kjs', 3, 'rectangular') ;
function test_auto_rect_kl1(), check_ker('kl1', 25, 'rectangular') ;
function test_gamma()
x = linspace(0,1,20) ;
for gamma = linspace(.2,2,10)
k = vl_alldist(x, 'kchi2') .* (x'*x + 1e-12).^((gamma-1)/2) ;
psix = vl_homkermap(x, 3, 'kchi2', 'gamma', gamma) ;
assert(norm(k - psix'*psix) < 1e-2) ;
end
function test_negative()
x = linspace(-1,1,20) ;
k = vl_alldist(abs(x), 'kchi2') .* (sign(x)'*sign(x)) ;
psix = vl_homkermap(x, 3, 'kchi2') ;
assert(norm(k - psix'*psix) < 1e-2) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_slic.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_slic.m
| 200 |
utf_8
|
12a6465e3ef5b4bcfd7303cd8a9229d4
|
function results = vl_test_slic(varargin)
% VL_TEST_SLIC
vl_test_init ;
function s = setup()
s.im = im2single(vl_impattern('roofs1')) ;
function test_slic(s)
segmentation = vl_slic(s.im, 10, 0.1) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_ikmeans.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_ikmeans.m
| 466 |
utf_8
|
1ee2f647ac0035ed0d704a0cd615b040
|
function results = vl_test_ikmeans(varargin)
% VL_TEST_IKMEANS
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(rand(2,1000) * 255) ;
function test_basic(s)
[centers, assign] = vl_ikmeans(s.data,100) ;
assign_ = vl_ikmeanspush(s.data, centers) ;
vl_assert_equal(assign,assign_) ;
function test_elkan(s)
[centers, assign] = vl_ikmeans(s.data,100,'method','elkan') ;
assign_ = vl_ikmeanspush(s.data, centers) ;
vl_assert_equal(assign,assign_) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_mser.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_mser.m
| 242 |
utf_8
|
1ad33563b0c86542a2978ee94e0f4a39
|
function results = vl_test_mser(varargin)
% VL_TEST_MSER
vl_test_init ;
function s = setup()
s.im = im2uint8(rgb2gray(vl_impattern('roofs1'))) ;
function test_mser(s)
[regions,frames] = vl_mser(s.im) ;
mask = vl_erfill(s.im, regions(1)) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_inthist.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_inthist.m
| 811 |
utf_8
|
459027d0c54d8f197563a02ab66ef45d
|
function results = vl_test_inthist(varargin)
% VL_TEST_INTHIST
vl_test_init ;
function s = setup()
rand('state',0) ;
s.labels = uint32(8*rand(123, 76, 3)) ;
function test_basic(s)
l = 10 ;
hist = vl_inthist(s.labels, 'numlabels', l) ;
hist_ = inthist_slow(s.labels, l) ;
vl_assert_equal(double(hist),hist_) ;
function test_sample(s)
rand('state',0) ;
boxes = 10 * rand(4,20) + .5 ;
boxes(3:4,:) = boxes(3:4,:) + boxes(1:2,:) ;
boxes = min(boxes, 10) ;
boxes = uint32(boxes) ;
inthist = vl_inthist(s.labels) ;
hist = vl_sampleinthist(inthist, boxes) ;
function hist = inthist_slow(labels, numLabels)
m = size(labels,1) ;
n = size(labels,2) ;
l = numLabels ;
b = zeros(m*n,l) ;
b = vl_binsum(b, 1, reshape(labels,m*n,[]), 2) ;
b = reshape(b,m,n,l) ;
for k=1:l
hist(:,:,k) = cumsum(cumsum(b(:,:,k)')') ;
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_imdisttf.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_imdisttf.m
| 1,885 |
utf_8
|
ae921197988abeb984cbcdf9eaf80e77
|
function results = vl_test_imdisttf(varargin)
% VL_TEST_DISTTF
vl_test_init ;
function test_basic()
for conv = {@single, @double}
conv = conv{1} ;
I = conv([0 0 0 ; 0 -2 0 ; 0 0 0]) ;
D = vl_imdisttf(I);
assert(isequal(D, conv(- [0 1 0 ; 1 2 1 ; 0 1 0]))) ;
I(2,2) = -3 ;
[D,map] = vl_imdisttf(I) ;
assert(isequal(D, conv(-1 - [0 1 0 ; 1 2 1 ; 0 1 0]))) ;
assert(isequal(map, 5 * ones(3))) ;
end
function test_1x1()
assert(isequal(1, vl_imdisttf(1))) ;
function test_rand()
I = rand(13,31) ;
for t=1:4
param = [rand randn rand randn] ;
[D0,map0] = imdisttf_equiv(I,param) ;
[D,map] = vl_imdisttf(I,param) ;
vl_assert_almost_equal(D,D0,1e-10)
assert(isequal(map,map0)) ;
end
function test_param()
I = zeros(3,4) ;
I(1,1) = -1 ;
[D,map] = vl_imdisttf(I,[1 0 1 0]);
assert(isequal(-[1 0 0 0 ;
0 0 0 0 ;
0 0 0 0 ;], D)) ;
D0 = -[1 .9 .6 .1 ;
0 0 0 0 ;
0 0 0 0 ;] ;
[D,map] = vl_imdisttf(I,[.1 0 1 0]);
vl_assert_almost_equal(D,D0,1e-10);
D0 = -[1 .9 .6 .1 ;
.9 .8 .5 0 ;
.6 .5 .2 0 ;] ;
[D,map] = vl_imdisttf(I,[.1 0 .1 0]);
vl_assert_almost_equal(D,D0,1e-10);
D0 = -[.9 1 .9 .6 ;
.8 .9 .8 .5 ;
.5 .6 .5 .2 ; ] ;
[D,map] = vl_imdisttf(I,[.1 1 .1 0]);
vl_assert_almost_equal(D,D0,1e-10);
function test_special()
I = rand(13,31) -.5 ;
D = vl_imdisttf(I, [0 0 1e5 0]) ;
vl_assert_almost_equal(D(:,1),min(I,[],2),1e-10);
D = vl_imdisttf(I, [1e5 0 0 0]) ;
vl_assert_almost_equal(D(1,:),min(I,[],1),1e-10);
function [D,map]=imdisttf_equiv(I,param)
D = inf + zeros(size(I)) ;
map = zeros(size(I)) ;
ur = 1:size(D,2) ;
vr = 1:size(D,1) ;
[u,v] = meshgrid(ur,vr) ;
for v_=vr
for u_=ur
E = I(v_,u_) + ...
param(1) * (u - u_ - param(2)).^2 + ...
param(3) * (v - v_ - param(4)).^2 ;
map(E < D) = sub2ind(size(I),v_,u_) ;
D = min(D,E) ;
end
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_vlad.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_vlad.m
| 1,977 |
utf_8
|
d3797288d6edb1d445b890db3780c8ce
|
function results = vl_test_vlad(varargin)
% VL_TEST_VLAD
vl_test_init ;
function s = setup()
randn('state',0) ;
s.x = randn(128,256) ;
s.mu = randn(128,16) ;
assignments = rand(16, 256) ;
s.assignments = bsxfun(@times, assignments, 1 ./ sum(assignments,1)) ;
function test_basic (s)
x = [1, 2, 3] ;
mu = [0, 0, 0] ;
assignments = eye(3) ;
phi = vl_vlad(x, mu, assignments, 'unnormalized') ;
vl_assert_equal(phi, [1 2 3]') ;
mu = [0, 1, 2] ;
phi = vl_vlad(x, mu, assignments, 'unnormalized') ;
vl_assert_equal(phi, [1 1 1]') ;
phi = vl_vlad([x x], mu, [assignments assignments], 'unnormalized') ;
vl_assert_equal(phi, [2 2 2]') ;
function test_rand (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized') ;
vl_assert_equal(phi, phi_) ;
function test_norm (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_vlad(s.x, s.mu, s.assignments) ;
vl_assert_almost_equal(phi, phi_, 1e-4) ;
function test_sqrt (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_vlad(s.x, s.mu, s.assignments, 'squareroot') ;
vl_assert_almost_equal(phi, phi_, 1e-4) ;
function test_individual (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi_ = reshape(phi_, size(s.x,1), []) ;
phi_ = bsxfun(@times, phi_, 1 ./ sqrt(sum(phi_.^2))) ;
phi_ = phi_(:) ;
phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizecomponents') ;
vl_assert_almost_equal(phi, phi_, 1e-4) ;
function test_mass (s)
phi_ = simple_vlad(s.x, s.mu, s.assignments) ;
phi_ = reshape(phi_, size(s.x,1), []) ;
phi_ = bsxfun(@times, phi_, 1 ./ sum(s.assignments,2)') ;
phi_ = phi_(:) ;
phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizemass') ;
vl_assert_almost_equal(phi, phi_, 1e-4) ;
function enc = simple_vlad(x, mu, assign)
for i = 1:size(assign,1)
enc{i} = x * assign(i,:)' - sum(assign(i,:)) * mu(:,i) ;
end
enc = cat(1, enc{:}) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_pr.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_pr.m
| 3,763 |
utf_8
|
4d1da5ccda1a7df2bec35b8f12fdd620
|
function results = vl_test_pr(varargin)
% VL_TEST_PR
vl_test_init ;
function s = setup()
s.scores0 = [5 4 3 2 1] ;
s.scores1 = [5 3 4 2 1] ;
s.labels = [1 1 -1 -1 -1] ;
function test_perfect_tptn(s)
[rc,pr] = vl_pr(s.labels,s.scores0) ;
vl_assert_almost_equal(pr, [1 1/1 2/2 2/3 2/4 2/5]) ;
vl_assert_almost_equal(rc, [0 1 2 2 2 2] / 2) ;
function test_perfect_metrics(s)
[rc,pr,info] = vl_pr(s.labels,s.scores0) ;
vl_assert_almost_equal(info.auc, 1) ;
vl_assert_almost_equal(info.ap, 1) ;
vl_assert_almost_equal(info.ap_interp_11, 1) ;
function test_swap1_tptn(s)
[rc,pr] = vl_pr(s.labels,s.scores1) ;
vl_assert_almost_equal(pr, [1 1/1 1/2 2/3 2/4 2/5]) ;
vl_assert_almost_equal(rc, [0 1 1 2 2 2] / 2) ;
function test_swap1_tptn_stable(s)
[rc,pr] = vl_pr(s.labels,s.scores1,'stable',true) ;
vl_assert_almost_equal(pr, [1/1 2/3 1/2 2/4 2/5]) ;
vl_assert_almost_equal(rc, [1 2 1 2 2] / 2) ;
function test_swap1_metrics(s)
[rc,pr,info] = vl_pr(s.labels,s.scores1) ;
clf; vl_pr(s.labels,s.scores1) ;
vl_assert_almost_equal(info.auc, [.5 + .5 * (.5 + 2/3)/2]) ;
vl_assert_almost_equal(info.ap, [1/1 + 2/3]/2) ;
vl_assert_almost_equal(info.ap_interp_11, mean([1 1 1 1 1 1 2/3 2/3 2/3 2/3 2/3])) ;
function test_inf(s)
scores = [1 -inf -1 -1 -1 -1] ;
labels = [1 1 -1 -1 -1 -1] ;
[rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true) ;
[rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false) ;
vl_assert_equal(numel(rc1), numel(rc2) + 1) ;
vl_assert_almost_equal(info1.auc, [1 * .5 + (1/5 + 2/6)/2 * .5]) ;
vl_assert_almost_equal(info1.ap, [1 * .5 + 2/6 * .5]) ;
vl_assert_almost_equal(info1.ap_interp_11, [1 * 6/11 + 2/6 * 5/11]) ;
vl_assert_almost_equal(info2.auc, 0.5) ;
vl_assert_almost_equal(info2.ap, 0.5) ;
vl_assert_almost_equal(info2.ap_interp_11, 1 * 6 / 11) ;
function test_inf_stable(s)
scores = [-1 -1 -1 -1 -inf +1] ;
labels = [-1 -1 -1 -1 +1 +1] ;
[rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true, 'stable', true) ;
[rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false, 'stable', true) ;
[rc1_,pr1_,info1_] = vl_pr(labels, scores, 'includeInf', true, 'stable', false) ;
[rc2_,pr2_,info2_] = vl_pr(labels, scores, 'includeInf', false, 'stable', false) ;
% stability does not change scores
vl_assert_almost_equal(info1,info1_) ;
vl_assert_almost_equal(info2,info2_) ;
% unstable with inf (first point (0,1) is conventional)
vl_assert_almost_equal(rc1_, [0 .5 .5 .5 .5 .5 1])
vl_assert_almost_equal(pr1_, [1 1 1/2 1/3 1/4 1/5 2/6])
% unstable without inf
vl_assert_almost_equal(rc2_, [0 .5 .5 .5 .5 .5])
vl_assert_almost_equal(pr2_, [1 1 1/2 1/3 1/4 1/5])
% stable with inf (no conventional point here)
vl_assert_almost_equal(rc1, [.5 .5 .5 .5 1 .5]) ;
vl_assert_almost_equal(pr1, [1/2 1/3 1/4 1/5 2/6 1]) ;
% stable without inf (no conventional point and -inf are NaN)
vl_assert_almost_equal(rc2, [.5 .5 .5 .5 NaN .5]) ;
vl_assert_almost_equal(pr2, [1/2 1/3 1/4 1/5 NaN 1]) ;
function test_normalised_pr(s)
scores = [+1 +2] ;
labels = [+1 -1] ;
[rc1,pr1,info1] = vl_pr(labels,scores) ;
[rc2,pr2,info2] = vl_pr(labels,scores,'normalizePrior',.5) ;
vl_assert_almost_equal(pr1, pr2) ;
vl_assert_almost_equal(rc1, rc2) ;
scores_ = [+1 +2 +2 +2] ;
labels_ = [+1 -1 -1 -1] ;
[rc3,pr3,info3] = vl_pr(labels_,scores_) ;
[rc4,pr4,info4] = vl_pr(labels,scores,'normalizePrior',1/4) ;
vl_assert_almost_equal(info3, info4) ;
function test_normalised_pr_corner_cases(s)
scores = 1:10 ;
labels = ones(1,10) ;
[rc1,pr1,info1] = vl_pr(labels,scores) ;
vl_assert_almost_equal(rc1, (0:10)/10) ;
vl_assert_almost_equal(pr1, ones(1,11)) ;
scores = 1:10 ;
labels = zeros(1,10) ;
[rc2,pr2,info2] = vl_pr(labels,scores) ;
vl_assert_almost_equal(rc2, zeros(1,11)) ;
vl_assert_almost_equal(pr2, ones(1,11)) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_hog.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_hog.m
| 1,555 |
utf_8
|
eed7b2a116d142040587dc9c4eb7cd2e
|
function results = vl_test_hog(varargin)
% VL_TEST_HOG
vl_test_init ;
function s = setup()
s.im = im2single(vl_impattern('roofs1')) ;
[x,y]= meshgrid(linspace(-1,1,128)) ;
s.round = single(x.^2+y.^2);
s.imSmall = s.im(1:128,1:128,:) ;
s.imSmall = s.im ;
s.imSmallFlipped = s.imSmall(:,end:-1:1,:) ;
function test_basic_call(s)
cellSize = 8 ;
hog = vl_hog(s.im, cellSize) ;
function test_bilinear_orientations(s)
cellSize = 8 ;
vl_hog(s.im, cellSize, 'bilinearOrientations') ;
function test_variants_and_flipping(s)
variants = {'uoctti', 'dalaltriggs'} ;
numOrientationsRange = 3:9 ;
cellSize = 8 ;
for cellSize = [4 8 16]
for i=1:numel(variants)
for j=1:numel(numOrientationsRange)
args = {'bilinearOrientations', ...
'variant', variants{i}, ...
'numOrientations', numOrientationsRange(j)} ;
hog = vl_hog(s.imSmall, cellSize, args{:}) ;
perm = vl_hog('permutation', args{:}) ;
hog1 = vl_hog(s.imSmallFlipped, cellSize, args{:}) ;
hog2 = hog(:,end:-1:1,perm) ;
%norm(hog1(:)-hog2(:))
vl_assert_almost_equal(hog1,hog2,1e-3) ;
end
end
end
function test_polar(s)
cellSize = 8 ;
im = s.round ;
for b = [0 1]
if b
args = {'bilinearOrientations'} ;
else
args = {} ;
end
hog1 = vl_hog(im, cellSize, args{:}) ;
[ix,iy] = vl_grad(im) ;
m = sqrt(ix.^2 + iy.^2) ;
a = atan2(iy,ix) ;
m(:,[1 end]) = 0 ;
m([1 end],:) = 0 ;
hog2 = vl_hog(cat(3,m,a), cellSize, 'DirectedPolarField', args{:}) ;
vl_assert_almost_equal(hog1,hog2,norm(hog1(:))/1000) ;
end
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_argparse.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_argparse.m
| 795 |
utf_8
|
e72185b27206d0ee1dfdc19fe77a5be6
|
function results = vl_test_argparse(varargin)
% VL_TEST_ARGPARSE
vl_test_init ;
function test_basic()
opts.field1 = 1 ;
opts.field2 = 2 ;
opts.field3 = 3 ;
opts_ = opts ;
opts_.field1 = 3 ;
opts_.field2 = 10 ;
opts = vl_argparse(opts, {'field2', 10, 'field1', 3}) ;
assert(isequal(opts, opts_)) ;
opts_.field1 = 9 ;
opts = vl_argparse(opts, {'field1', 4, 'field1', 9}) ;
assert(isequal(opts, opts_)) ;
function test_error()
opts.field1 = 1 ;
try
opts = vl_argparse(opts, {'field2', 5}) ;
catch e
return ;
end
assert(false) ;
function test_leftovers()
opts1.field1 = 1 ;
opts2.field2 = 1 ;
opts1_.field1 = 2 ;
opts2_.field2 = 2 ;
[opts1,args] = vl_argparse(opts1, {'field1', 2, 'field2', 2}) ;
opts2 = vl_argparse(opts2, args) ;
assert(isequal(opts1,opts1_), isequal(opts2,opts2_)) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_liop.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_liop.m
| 1,023 |
utf_8
|
a162be369073bed18e61210f44088cf3
|
function results = vl_test_liop(varargin)
% VL_TEST_SIFT
vl_test_init ;
function s = setup()
randn('state',0) ;
s.patch = randn(65,'single') ;
xr = -32:32 ;
[x,y] = meshgrid(xr) ;
s.blob = - single(x.^2+y.^2) ;
function test_basic(s)
d = vl_liop(s.patch) ;
function test_blob(s)
% with a blob, all local intensity order pattern are equal. In
% particular, if the blob intensity decreases away from the center,
% then all local intensities sampled in a neighbourhood of 2 elements
% are already sorted (see LIOP details).
d = vl_liop(s.blob, ...
'IntensityThreshold', 0, ...
'NumNeighbours', 2, ...
'NumSpatialBins', 1) ;
assert(isequal(d, single([1;0]))) ;
function test_neighbours(s)
for n=2:5
for p=1:3
d = vl_liop(s.patch, 'NumNeighbours', n, 'NumSpatialBins', p) ;
assert(numel(d) == p * factorial(n)) ;
end
end
function test_multiple(s)
x = randn(31,31,3, 'single') ;
d = vl_liop(x) ;
for i=1:3
d_(:,i) = vl_liop(squeeze(x(:,:,i))) ;
end
assert(isequal(d,d_)) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_test_binsearch.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/xtest/vl_test_binsearch.m
| 1,339 |
utf_8
|
85dc020adce3f228fe7dfb24cf3acc63
|
function results = vl_test_binsearch(varargin)
% VL_TEST_BINSEARCH
vl_test_init ;
function test_inf_bins()
x = [-inf -1 0 1 +inf] ;
vl_assert_equal(vl_binsearch([], x), [0 0 0 0 0]) ;
vl_assert_equal(vl_binsearch([-inf 0], x), [1 1 2 2 2]) ;
vl_assert_equal(vl_binsearch([-inf], x), [1 1 1 1 1]) ;
vl_assert_equal(vl_binsearch([-inf +inf], x), [1 1 1 1 2]) ;
function test_empty()
vl_assert_equal(vl_binsearch([], []), []) ;
function test_bnd()
vl_assert_equal(vl_binsearch([], [1]), [0]) ;
vl_assert_equal(vl_binsearch([], [-inf]), [0]) ;
vl_assert_equal(vl_binsearch([], [+inf]), [0]) ;
vl_assert_equal(vl_binsearch([1], [.9]), [0]) ;
vl_assert_equal(vl_binsearch([1], [1]), [1]) ;
vl_assert_equal(vl_binsearch([1], [-inf]), [0]) ;
vl_assert_equal(vl_binsearch([1], [+inf]), [1]) ;
function test_basic()
vl_assert_equal(vl_binsearch(-10:10, -10:10), 1:21) ;
vl_assert_equal(vl_binsearch(-10:10, -11:10), 0:21) ;
vl_assert_equal(vl_binsearch(-10:10, [-inf, -11:10, +inf]), [0 0:21 21]) ;
function test_frac()
vl_assert_equal(vl_binsearch(1:10, 1:.5:10), floor(1:.5:10))
vl_assert_equal(vl_binsearch(1:10, fliplr(1:.5:10)), ...
fliplr(floor(1:.5:10))) ;
function test_array()
a = reshape(1:100,10,10) ;
b = reshape(1:.5:100.5, 2, []) ;
c = floor(b) ;
vl_assert_equal(vl_binsearch(a,b), c) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_roc.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/plotop/vl_roc.m
| 10,113 |
utf_8
|
22fd8ff455ee62a96ffd94b9074eafeb
|
function [tpr,tnr,info] = vl_roc(labels, scores, varargin)
%VL_ROC ROC curve.
% [TPR,TNR] = VL_ROC(LABELS, SCORES) computes the Receiver Operating
% Characteristic (ROC) curve [1]. LABELS is a row vector of ground
% truth labels, greater than zero for a positive sample and smaller
% than zero for a negative one. SCORES is a row vector of
% corresponding sample scores, usually obtained from a
% classifier. The scores induce a ranking of the samples where
% larger scores should correspond to positive labels.
%
% Without output arguments, the function plots the ROC graph of the
% specified data in the current graphical axis.
%
% Otherwise, the function returns the true positive and true
% negative rates TPR and TNR. These are vectors of the same size of
% LABELS and SCORES and are computed as follows. Samples are ranked
% by decreasing scores, starting from rank 1. TPR(K) and TNR(K) are
% the true positive and true negative rates when samples of rank
% smaller or equal to K-1 are predicted to be positive. So for
% example TPR(3) is the true positive rate when the two samples with
% largest score are predicted to be positive. Similarly, TPR(1) is
% the true positive rate when no samples are predicted to be
% positive, i.e. the constant 0.
%
% Setting a label to zero ignores the corresponding sample in the
% calculations, as if the sample was removed from the data. Setting
% the score of a sample to -INF causes the function to assume that
% that sample was never retrieved. If there are samples with -INF
% score, the ROC curve is incomplete as the maximum recall is less
% than 1.
%
% [TPR,TNR,INFO] = VL_ROC(...) returns an additional structure INFO
% with the following fields:
%
% info.auc:: Area under the ROC curve (AUC).
% This is the area under the ROC plot, the parametric curve
% (FPR(S), TPR(S)). The PLOT option can be used to plot variants
% of this curve, which affects the calculation of a corresponding
% AUC.
%
% info.eer:: Equal error rate (EER).
% The equal error rate is the value of FPR (or FNR) when the ROC
% curves intersects the line connecting (0,0) to (1,1).
%
% info.eerThreshold:: EER threshold.
% The value of the score for which the EER is attained.
%
% VL_ROC() accepts the following options:
%
% Plot:: []
% Setting this option turns on plotting unconditionally. The
% following plot variants are supported:
%
% tntp:: Plot TPR against TNR (standard ROC plot).
% tptn:: Plot TNR against TPR (recall on the horizontal axis).
% fptp:: Plot TPR against FPR.
% fpfn:: Plot FNR against FPR (similar to a DET curve).
%
% Note that this option will affect the INFO.AUC value computation
% too.
%
% NumPositives:: []
% NumNegatives:: []
% If either of these parameters is set to a number, the function
% pretends that LABELS contains the specified number of
% positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be
% smaller than the actual number of positive/negative entries in
% LABELS. The additional positive/negative labels are appended to
% the end of the sequence as if they had -INF scores (as explained
% above, the function interprets such samples as `not
% retrieved'). This feature can be used to evaluate the
% performance of a large-scale retrieval experiment in which only
% a subset of highly-scoring results are recorded for efficiency
% reason.
%
% Stable:: false
% If set to true, TPR and TNR are returned in the same order
% of LABELS and SCORES rather than being sorted by decreasing
% score.
%
% About the ROC curve::
% Consider a classifier that predicts as positive all samples whose
% score is not smaller than a threshold S. The ROC curve represents
% the performance of such classifier as the threshold S is
% changed. Formally, define
%
% P = overall num. of positive samples,
% N = overall num. of negative samples,
%
% and for each threshold S
%
% TP(S) = num. of samples that are correctly classified as positive,
% TN(S) = num. of samples that are correctly classified as negative,
% FP(S) = num. of samples that are incorrectly classified as positive,
% FN(S) = num. of samples that are incorrectly classified as negative.
%
% Consider also the rates:
%
% TPR = TP(S) / P, FNR = FN(S) / P,
% TNR = TN(S) / N, FPR = FP(S) / N,
%
% and notice that, by definition,
%
% P = TP(S) + FN(S) , N = TN(S) + FP(S),
% 1 = TPR(S) + FNR(S), 1 = TNR(S) + FPR(S).
%
% The ROC curve is the parametric curve (FPR(S), TPR(S)) obtained
% as the classifier threshold S is varied in the reals. The TPR is
% the same as `recall' in a PR curve (see VL_PR()).
%
% The ROC curve is contained in the square with vertices (0,0) The
% (average) ROC curve of a random classifier is a line which
% connects (1,0) and (0,1).
%
% The ROC curve is independent of the prior probability of the
% labels (i.e. of P/(P+N) and N/(P+N)).
%
% REFERENCES:
% [1] http://en.wikipedia.org/wiki/Receiver_operating_characteristic
%
% See also: VL_PR(), VL_DET(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
[tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ;
opts.plot = [] ;
opts.stable = false ;
opts = vl_argparse(opts,varargin) ;
% compute the rates
small = 1e-10 ;
tpr = tp / max(p, small) ;
fpr = fp / max(n, small) ;
fnr = 1 - tpr ;
tnr = 1 - fpr ;
do_plots = ~isempty(opts.plot) || nargout == 0 ;
if isempty(opts.plot), opts.plot = 'fptp' ; end
% --------------------------------------------------------------------
% Additional info
% --------------------------------------------------------------------
if nargout > 2 || do_plots
% Area under the curve. Since the curve is a staircase (in the
% sense that for each sample either tn is decremented by one
% or tp is incremented by one but the other remains fixed),
% the integral is particularly simple and exact.
switch opts.plot
case 'tntp', info.auc = -sum(tpr .* diff([0 tnr])) ;
case 'fptp', info.auc = +sum(tpr .* diff([0 fpr])) ;
case 'tptn', info.auc = +sum(tnr .* diff([0 tpr])) ;
case 'fpfn', info.auc = +sum(fnr .* diff([0 fpr])) ;
otherwise
error('''%s'' is not a valid PLOT type.', opts.plot);
end
% Equal error rate. One must find the index S in correspondence of
% which TNR(S) and TPR(s) cross. Note that TPR(S) is non-decreasing,
% TNR(S) is non-increasing, and from rank S to rank S+1 only one of
% the two quantities can change. Hence there are exactly two types
% of crossing points:
%
% 1) TNR(S) = TNR(S+1) = EER and TPR(S) <= EER, TPR(S+1) > EER,
% 2) TPR(S) = TPR(S+1) = EER and TNR(S) > EER, TNR(S+1) <= EER.
%
% Moreover, if the maximum TPR is smaller than 1, then it is
% possible that neither of the two cases realizes. In the latter
% case, we return EER=NaN.
s = max(find(tnr > tpr)) ;
if s == length(tpr)
info.eer = NaN ;
info.eerThreshold = 0 ;
else
if tpr(s) == tpr(s+1)
info.eer = 1 - tpr(s) ;
else
info.eer = 1 - tnr(s) ;
end
info.eerThreshold = scores(perm(s)) ;
end
end
% --------------------------------------------------------------------
% Plot
% --------------------------------------------------------------------
if do_plots
cla ; hold on ;
switch lower(opts.plot)
case 'tntp'
hroc = plot(tnr, tpr, 'b', 'linewidth', 2) ;
hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ;
spline([0 1], [0 1], 'k--', 'linewidth', 1) ;
plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ;
xlabel('true negative rate') ;
ylabel('true positive rate (recall)') ;
loc = 'sw' ;
case 'fptp'
hroc = plot(fpr, tpr, 'b', 'linewidth', 2) ;
hrand = spline([0 1], [0 1], 'r--', 'linewidth', 2) ;
spline([1 0], [0 1], 'k--', 'linewidth', 1) ;
plot(info.eer, 1-info.eer, 'k*', 'linewidth', 1) ;
xlabel('false positive rate') ;
ylabel('true positive rate (recall)') ;
loc = 'se' ;
case 'tptn'
hroc = plot(tpr, tnr, 'b', 'linewidth', 2) ;
hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ;
spline([0 1], [0 1], 'k--', 'linewidth', 1) ;
plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ;
xlabel('true positive rate (recall)') ;
ylabel('false positive rate') ;
loc = 'sw' ;
case 'fpfn'
hroc = plot(fpr, fnr, 'b', 'linewidth', 2) ;
hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ;
spline([0 1], [0 1], 'k--', 'linewidth', 1) ;
plot(info.eer, info.eer, 'k*', 'linewidth', 1) ;
xlabel('false positive (false alarm) rate') ;
ylabel('false negative (miss) rate') ;
loc = 'ne' ;
otherwise
error('''%s'' is not a valid PLOT type.', opts.plot);
end
grid on ;
xlim([0 1]) ;
ylim([0 1]) ;
axis square ;
title(sprintf('ROC (AUC: %.2f%%, EER: %.2f%%)', info.auc * 100, info.eer * 100), ...
'interpreter', 'none') ;
legend([hroc hrand], 'ROC', 'ROC rand.', 'location', loc) ;
end
% --------------------------------------------------------------------
% Stable output
% --------------------------------------------------------------------
if opts.stable
tpr(1) = [] ;
tnr(1) = [] ;
tpr_ = tpr ;
tnr_ = tnr ;
tpr = NaN(size(tpr)) ;
tnr = NaN(size(tnr)) ;
tpr(perm) = tpr_ ;
tnr(perm) = tnr_ ;
end
% --------------------------------------------------------------------
function h = spline(x,y,spec,varargin)
% --------------------------------------------------------------------
prop = vl_linespec2prop(spec) ;
h = line(x,y,prop{:},varargin{:}) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_click.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/plotop/vl_click.m
| 2,661 |
utf_8
|
6982e869cf80da57fdf68f5ebcd05a86
|
function P = vl_click(N,varargin) ;
% VL_CLICK Click a point
% P=VL_CLICK() let the user click a point in the current figure and
% returns its coordinates in P. P is a two dimensiona vectors where
% P(1) is the point X-coordinate and P(2) the point Y-coordinate. The
% user can abort the operation by pressing any key, in which case the
% empty matrix is returned.
%
% P=VL_CLICK(N) lets the user select N points in a row. The user can
% stop inserting points by pressing any key, in which case the
% partial list is returned.
%
% VL_CLICK() accepts the following options:
%
% PlotMarker:: [0]
% Plot a marker as points are selected. The markers are deleted on
% exiting the function.
%
% See also: VL_CLICKPOINT(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
plot_marker = 0 ;
for k=1:2:length(varargin)
switch lower(varargin{k})
case 'plotmarker'
plot_marker = varargin{k+1} ;
otherwise
error(['Uknown option ''', varargin{k}, '''.']) ;
end
end
if nargin < 1
N=1;
end
% --------------------------------------------------------------------
% Do job
% --------------------------------------------------------------------
fig = gcf ;
is_hold = ishold ;
hold on ;
bhandler = get(fig,'WindowButtonDownFcn') ;
khandler = get(fig,'KeyPressFcn') ;
pointer = get(fig,'Pointer') ;
set(fig,'WindowButtonDownFcn',@click_handler) ;
set(fig,'KeyPressFcn',@key_handler) ;
set(fig,'Pointer','crosshair') ;
P=[] ;
h=[] ;
data.exit=0;
guidata(fig,data) ;
while size(P,2) < N
uiwait(fig) ;
data = guidata(fig) ;
if(data.exit)
break ;
end
P = [P data.P] ;
if( plot_marker )
h=[h plot(data.P(1),data.P(2),'rx')] ;
end
end
if ~is_hold
hold off ;
end
if( plot_marker )
pause(.1);
delete(h) ;
end
set(fig,'WindowButtonDownFcn',bhandler) ;
set(fig,'KeyPressFcn',khandler) ;
set(fig,'Pointer',pointer) ;
% ====================================================================
function click_handler(obj,event)
% --------------------------------------------------------------------
data = guidata(gcbo) ;
P = get(gca, 'CurrentPoint') ;
P = [P(1,1); P(1,2)] ;
data.P = P ;
guidata(obj,data) ;
uiresume(gcbo) ;
% ====================================================================
function key_handler(obj,event)
% --------------------------------------------------------------------
data = guidata(gcbo) ;
data.exit = 1 ;
guidata(obj,data) ;
uiresume(gcbo) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_pr.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/plotop/vl_pr.m
| 9,138 |
utf_8
|
c7fe6832d2b6b9917896810c52a05479
|
function [recall, precision, info] = vl_pr(labels, scores, varargin)
%VL_PR Precision-recall curve.
% [RECALL, PRECISION] = VL_PR(LABELS, SCORES) computes the
% precision-recall (PR) curve. LABELS are the ground truth labels,
% greather than zero for a positive sample and smaller than zero for
% a negative one. SCORES are the scores of the samples obtained from
% a classifier, where lager scores should correspond to positive
% samples.
%
% Samples are ranked by decreasing scores, starting from rank 1.
% PRECISION(K) and RECALL(K) are the precison and recall when
% samples of rank smaller or equal to K-1 are predicted to be
% positive and the remaining to be negative. So for example
% PRECISION(3) is the percentage of positive samples among the two
% samples with largest score. PRECISION(1) is the precision when no
% samples are predicted to be positive and is conventionally set to
% the value 1.
%
% Set to zero the lables of samples that should be ignored in the
% evaluation. Set to -INF the scores of samples which are not
% retrieved. If there are samples with -INF score, then the PR curve
% may have maximum recall smaller than 1, unless the INCLUDEINF
% option is used (see below). The options NUMNEGATIVES and
% NUMPOSITIVES can be used to add additional surrogate samples with
% -INF score (see below).
%
% [RECALL, PRECISION, INFO] = VL_PR(...) returns an additional
% structure INFO with the following fields:
%
% info.auc::
% The area under the precision-recall curve. If the INTERPOLATE
% option is set to FALSE, then trapezoidal interpolation is used
% to integrate the PR curve. If the INTERPOLATE option is set to
% TRUE, then the curve is piecewise constant and no other
% approximation is introduced in the calculation of the area. In
% the latter case, INFO.AUC is the same as INFO.AP.
%
% info.ap::
% Average precision as defined by TREC. This is the average of the
% precision observed each time a new positive sample is
% recalled. In this calculation, any sample with -INF score
% (unless INCLUDEINF is used) and any additional positive induced
% by NUMPOSITIVES has precision equal to zero. If the INTERPOLATE
% option is set to true, the AP is computed from the interpolated
% precision and the result is the same as INFO.AUC. Note that AP
% as defined by TREC normally does not use interpolation [1].
%
% info.ap_interp_11::
% 11-points interpolated average precision as defined by TREC.
% This is the average of the maximum precision for recall levels
% greather than 0.0, 0.1, 0.2, ..., 1.0. This measure was used in
% the PASCAL VOC challenge up to the 2008 edition.
%
% info.auc_pa08::
% Deprecated. It is the same of INFO.AP_INTERP_11.
%
% VL_PR(...) with no output arguments plots the PR curve in the
% current axis.
%
% VL_PR() accepts the following options:
%
% Interpolate:: false
% If set to true, use interpolated precision. The interpolated
% precision is defined as the maximum precision for a given recall
% level and onwards. Here it is implemented as the culumative
% maximum from low to high scores of the precision.
%
% NumPositives:: []
% NumNegatives:: []
% If set to a number, pretend that LABELS contains this may
% positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be
% smaller than the actual number of positive/negative entrires in
% LABELS. The additional positive/negative labels are appended to
% the end of the sequence, as if they had -INF scores (not
% retrieved). This is useful to evaluate large retrieval systems
% for which one stores ony a handful of top results for efficiency
% reasons.
%
% IncludeInf:: false
% If set to true, data with -INF score SCORES is included in the
% evaluation and the maximum recall is 1 even if -INF scores are
% present. This option does not include any additional positive or
% negative data introduced by specifying NUMPOSITIVES and
% NUMNEGATIVES.
%
% Stable:: false
% If set to true, RECALL and PRECISION are returned in the same order
% of LABELS and SCORES rather than being sorted by decreasing
% score (increasing recall). Samples with -INF scores are assigned
% RECALL and PRECISION equal to NaN.
%
% NormalizePrior:: []
% If set to a scalar, reweights positive and negative labels so
% that the fraction of positive ones is equal to the specified
% value. This computes the normalised PR curves of [2]
%
% About the PR curve::
% This section uses the same symbols used in the documentation of
% the VL_ROC() function. In addition to those quantities, define:
%
% PRECISION(S) = TP(S) / (TP(S) + FP(S))
% RECALL(S) = TPR(S) = TP(S) / P
%
% The precision is the fraction of positivie predictions which are
% correct, and the recall is the fraction of positive labels that
% have been correctly classified (recalled). Notice that the recall
% is also equal to the true positive rate for the ROC curve (see
% VL_ROC()).
%
% REFERENCES:
% [1] C. D. Manning, P. Raghavan, and H. Schutze. An Introduction to
% Information Retrieval. Cambridge University Press, 2008.
% [2] D. Hoiem, Y. Chodpathumwan, and Q. Dai. Diagnosing error in
% object detectors. In Proc. ECCV, 2012.
%
% See also VL_ROC(), VL_HELP().
% Author: Andrea Vedaldi
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
% TP and FP are the vectors of true positie and false positve label
% counts for decreasing scores, P and N are the total number of
% positive and negative labels. Note that if certain options are used
% some labels may actually not be stored explicitly by LABELS, so P+N
% can be larger than the number of element of LABELS.
[tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ;
opts.stable = false ;
opts.interpolate = false ;
opts.normalizePrior = [] ;
opts = vl_argparse(opts,varargin) ;
% compute precision and recall
small = 1e-10 ;
recall = tp / max(p, small) ;
if isempty(opts.normalizePrior)
precision = max(tp, small) ./ max(tp + fp, small) ;
else
a = opts.normalizePrior ;
precision = max(tp * a/max(p,small), small) ./ ...
max(tp * a/max(p,small) + fp * (1-a)/max(n,small), small) ;
end
% interpolate precision if needed
if opts.interpolate
precision = fliplr(vl_cummax(fliplr(precision))) ;
end
% --------------------------------------------------------------------
% Additional info
% --------------------------------------------------------------------
if nargout > 2 || nargout == 0
% area under the curve using trapezoid interpolation
if ~opts.interpolate
info.auc = 0.5 * sum((precision(1:end-1) + precision(2:end)) .* diff(recall)) ;
end
% average precision (for each recalled positive sample)
sel = find(diff(recall)) + 1 ;
info.ap = sum(precision(sel)) / p ;
if opts.interpolate
info.auc = info.ap ;
end
% TREC 11 points average interpolated precision
info.ap_interp_11 = 0.0 ;
for rc = linspace(0,1,11)
pr = max([0, precision(recall >= rc)]) ;
info.ap_interp_11 = info.ap_interp_11 + pr / 11 ;
end
% legacy definition
info.auc_pa08 = info.ap_interp_11 ;
end
% --------------------------------------------------------------------
% Plot
% --------------------------------------------------------------------
if nargout == 0
cla ; hold on ;
plot(recall,precision,'linewidth',2) ;
if isempty(opts.normalizePrior)
randomPrecision = p / (p + n) ;
else
randomPrecision = opts.normalizePrior ;
end
spline([0 1], [1 1] * randomPrecision, 'r--', 'linewidth', 2) ;
axis square ; grid on ;
xlim([0 1]) ; xlabel('recall') ;
ylim([0 1]) ; ylabel('precision') ;
title(sprintf('PR (AUC: %.2f%%, AP: %.2f%%, AP11: %.2f%%)', ...
info.auc * 100, ...
info.ap * 100, ...
info.ap_interp_11 * 100)) ;
if opts.interpolate
legend('PR interp.', 'PR rand.', 'Location', 'SouthEast') ;
else
legend('PR', 'PR rand.', 'Location', 'SouthEast') ;
end
clear recall precision info ;
end
% --------------------------------------------------------------------
% Stable output
% --------------------------------------------------------------------
if opts.stable
precision(1) = [] ;
recall(1) = [] ;
precision_ = precision ;
recall_ = recall ;
precision = NaN(size(precision)) ;
recall = NaN(size(recall)) ;
precision(perm) = precision_ ;
recall(perm) = recall_ ;
end
% --------------------------------------------------------------------
function h = spline(x,y,spec,varargin)
% --------------------------------------------------------------------
prop = vl_linespec2prop(spec) ;
h = line(x,y,prop{:},varargin{:}) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_ubcread.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/sift/vl_ubcread.m
| 3,015 |
utf_8
|
e8ddd3ecd87e76b6c738ba153fef050f
|
function [f,d] = vl_ubcread(file, varargin)
% SIFTREAD Read Lowe's SIFT implementation data files
% [F,D] = VL_UBCREAD(FILE) reads the frames F and the descriptors D
% from FILE in UBC (Lowe's original implementation of SIFT) format
% and returns F and D as defined by VL_SIFT().
%
% VL_UBCREAD(FILE, 'FORMAT', 'OXFORD') assumes the format used by
% Oxford VGG implementations .
%
% See also: VL_SIFT(), VL_HELP().
% Authors: Andrea Vedaldi
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.verbosity = 0 ;
opts.format = 'ubc' ;
opts = vl_argparse(opts, varargin) ;
g = fopen(file, 'r');
if g == -1
error(['Could not open file ''', file, '''.']) ;
end
[header, count] = fscanf(g, '%d', [1 2]) ;
if count ~= 2
error('Invalid keypoint file header.');
end
switch opts.format
case 'ubc'
numKeypoints = header(1) ;
descrLen = header(2) ;
case 'oxford'
numKeypoints = header(2) ;
descrLen = header(1) ;
otherwise
error('Unknown format ''%s''.', opts.format) ;
end
if(opts.verbosity > 0)
fprintf('%d keypoints, %d descriptor length.\n', numKeypoints, descrLen) ;
end
%creates two output matrices
switch opts.format
case 'ubc'
P = zeros(4,numKeypoints) ;
case 'oxford'
P = zeros(5,numKeypoints) ;
end
L = zeros(descrLen, numKeypoints) ;
%parse tmp.key
for k = 1:numKeypoints
switch opts.format
case 'ubc'
% Record format: i,j,s,th
[record, count] = fscanf(g, '%f', [1 4]) ;
if count ~= 4
error(...
sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) );
end
P(:,k) = record(:) ;
case 'oxford'
% Record format: x, y, a, b, c such that x' [a b ; b c] x = 1
[record, count] = fscanf(g, '%f', [1 5]) ;
if count ~= 5
error(...
sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) );
end
P(:,k) = record(:) ;
end
% Record format: descriptor
[record, count] = fscanf(g, '%d', [1 descrLen]) ;
if count ~= descrLen
error(...
sprintf('Invalid keypoint file (parsing keypoint %d, descriptor part)',k) );
end
L(:,k) = record(:) ;
end
fclose(g) ;
switch opts.format
case 'ubc'
P(1:2,:) = flipud(P(1:2,:)) + 1 ; % i,j -> x,y
f=[ P(1:2,:) ; P(3,:) ; -P(4,:) ] ;
d=uint8(L) ;
p=[1 2 3 4 5 6 7 8] ;
q=[1 8 7 6 5 4 3 2] ;
for j=0:3
for i=0:3
d(8*(i+4*j)+p,:) = d(8*(i+4*j)+q,:) ;
end
end
case 'oxford'
P(1:2,:) = P(1:2,:) + 1 ; % matlab origin
f = P ;
f(3:5,:) = inv2x2(f(3:5,:)) ;
d = uint8(L) ;
end
% --------------------------------------------------------------------
function S = inv2x2(C)
% --------------------------------------------------------------------
den = C(1,:) .* C(3,:) - C(2,:) .* C(2,:) ;
S = [C(3,:) ; -C(2,:) ; C(1,:)] ./ den([1 1 1], :) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_frame2oell.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/sift/vl_frame2oell.m
| 2,806 |
utf_8
|
c93792632f630743485fa4c2cf12d647
|
function eframes = vl_frame2oell(frames)
% VL_FRAMES2OELL Convert a geometric frame to an oriented ellipse
% EFRAME = VL_FRAME2OELL(FRAME) converts the generic FRAME to an
% oriented ellipses EFRAME. FRAME and EFRAME can be matrices, with
% one frame per column.
%
% A frame is either a point, a disc, an oriented disc, an ellipse,
% or an oriented ellipse. These are represented respectively by 2,
% 3, 4, 5 and 6 parameters each, as described in VL_PLOTFRAME(). An
% oriented ellipse is the most general geometric frame; hence, there
% is no loss of information in this conversion.
%
% If FRAME is an oriented disc or ellipse, then the conversion is
% immediate. If, however, FRAME is not oriented (it is either a
% point or an unoriented disc or ellipse), then an orientation must
% be assigned. The orientation is chosen in such a way that the
% affine transformation that maps the standard oriented frame into
% the output EFRAME does not rotate the Y axis. If frames represent
% detected visual features, this convention corresponds to assume
% that features are upright.
%
% If FRAME is a point, then the output is an ellipse with null area.
%
% See: <a href="matlab:vl_help('tut.frame')">feature frames</a>,
% VL_PLOTFRAME(), VL_HELP().
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
[D,K] = size(frames) ;
eframes = zeros(6,K) ;
switch D
case 2
eframes(1:2,:) = frames(1:2,:) ;
case 3
eframes(1:2,:) = frames(1:2,:) ;
eframes(3,:) = frames(3,:) ;
eframes(6,:) = frames(3,:) ;
case 4
r = frames(3,:) ;
c = r.*cos(frames(4,:)) ;
s = r.*sin(frames(4,:)) ;
eframes(1:2,:) = frames(1:2,:) ;
eframes(3:6,:) = [c ; s ; -s ; c] ;
case 5
eframes(1:2,:) = frames(1:2,:) ;
eframes(3:6,:) = mapFromS(frames(3:5,:)) ;
case 6
eframes = frames ;
otherwise
error('FRAMES format is unknown.') ;
end
% --------------------------------------------------------------------
function A = mapFromS(S)
% --------------------------------------------------------------------
% Returns the (stacking of the) 2x2 matrix A that maps the unit circle
% into the ellipses satisfying the equation x' inv(S) x = 1. Here S
% is a stacked covariance matrix, with elements S11, S12 and S22.
%
% The goal is to find A such that AA' = S. In order to let the Y
% direction unaffected (upright feature), the assumption is taht
% A = [a b ; 0 c]. Hence
%
% AA' = [a^2, ab ; ab, b^2+c^2] = S.
A = zeros(4,size(S,2)) ;
a = sqrt(S(1,:));
b = S(2,:) ./ max(a, 1e-18) ;
A(1,:) = a ;
A(2,:) = b ;
A(4,:) = sqrt(max(S(3,:) - b.*b, 0)) ;
|
github
|
sabbiu/ObjectDetection-master
|
vl_plotsiftdescriptor.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/toolbox/sift/vl_plotsiftdescriptor.m
| 5,114 |
utf_8
|
a4e125a8916653f00143b61cceda2f23
|
function h=vl_plotsiftdescriptor(d,f,varargin)
% VL_PLOTSIFTDESCRIPTOR Plot SIFT descriptor
% VL_PLOTSIFTDESCRIPTOR(D) plots the SIFT descriptor D. If D is a
% matrix, it plots one descriptor per column. D has the same format
% used by VL_SIFT().
%
% VL_PLOTSIFTDESCRIPTOR(D,F) plots the SIFT descriptors warped to
% the SIFT frames F, specified as columns of the matrix F. F has the
% same format used by VL_SIFT().
%
% H=VL_PLOTSIFTDESCRIPTOR(...) returns the handle H to the line
% drawing representing the descriptors.
%
% The function assumes that the SIFT descriptors use the standard
% configuration of 4x4 spatial bins and 8 orientations bins. The
% following parameters can be used to change this:
%
% NumSpatialBins:: 4
% Number of spatial bins in both spatial directions X and Y.
%
% NumOrientationBins:: 8
% Number of orientation bis.
%
% MagnificationFactor:: 3
% Magnification factor. The width of one bin is equal to the scale
% of the keypoint F multiplied by this factor.
%
% See also: VL_SIFT(), VL_PLOTFRAME(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.magnificationFactor = 3.0 ;
opts.numSpatialBins = 4 ;
opts.numOrientationBins = 8 ;
opts.maxValue = 0 ;
if nargin > 1
if ~ isnumeric(f)
error('F must be a numeric type (use [] to leave it unspecified)') ;
end
end
opts = vl_argparse(opts, varargin) ;
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
if(size(d,1) ~= opts.numSpatialBins^2 * opts.numOrientationBins)
error('The number of rows of D does not match the geometry of the descriptor') ;
end
if nargin > 1
if (~isempty(f) & (size(f,1) < 2 | size(f,1) > 6))
error('F must be either empty of have from 2 to six rows.');
end
if size(f,1) == 2
% translation only
f(3:6,:) = deal([10 0 0 10]') ;
%f = [f; 10 * ones(1, size(f,2)) ; 0 * zeros(1, size(f,2))] ;
end
if size(f,1) == 3
% translation and scale
f(3:6,:) = [1 0 0 1]' * f(3,:) ;
%f = [f; 0 * zeros(1, size(f,2))] ;
end
if size(f,1) == 4
c = cos(f(4,:)) ;
s = sin(f(4,:)) ;
f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ;
end
if size(f,1) == 5
assert(false) ;
c = cos(f(4,:)) ;
s = sin(f(4,:)) ;
f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ;
end
if(~isempty(f) & size(f,2) ~= size(d,2))
error('D and F have incompatible dimension') ;
end
end
% Descriptors are often non-double numeric arrays
d = double(d) ;
K = size(d,2) ;
if nargin < 2 | isempty(f)
f = repmat([0;0;1;0;0;1],1,K) ;
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
xall=[] ;
yall=[] ;
for k=1:K
[x,y] = render_descr(d(:,k), opts.numSpatialBins, opts.numOrientationBins, opts.maxValue) ;
xall = [xall opts.magnificationFactor*f(3,k)*x + opts.magnificationFactor*f(5,k)*y + f(1,k)] ;
yall = [yall opts.magnificationFactor*f(4,k)*x + opts.magnificationFactor*f(6,k)*y + f(2,k)] ;
end
h=line(xall,yall) ;
% --------------------------------------------------------------------
function [x,y] = render_descr(d, numSpatialBins, numOrientationBins, maxValue)
% --------------------------------------------------------------------
% Get the coordinates of the lines of the SIFT grid; each bin has side 1
[x,y] = meshgrid(-numSpatialBins/2:numSpatialBins/2,-numSpatialBins/2:numSpatialBins/2) ;
% Get the corresponding bin centers
xc = x(1:end-1,1:end-1) + 0.5 ;
yc = y(1:end-1,1:end-1) + 0.5 ;
% Rescale the descriptor range so that the biggest peak fits inside the bin diagram
if maxValue
d = 0.4 * d / maxValue ;
else
d = 0.4 * d / max(d(:)+eps) ;
end
% We scramble the the centers to have them in row major order
% (descriptor convention).
xc = xc' ;
yc = yc' ;
% Each spatial bin contains a star with numOrientationBins tips
xc = repmat(xc(:)',numOrientationBins,1) ;
yc = repmat(yc(:)',numOrientationBins,1) ;
% Do the stars
th=linspace(0,2*pi,numOrientationBins+1) ;
th=th(1:end-1) ;
xd = repmat(cos(th), 1, numSpatialBins*numSpatialBins) ;
yd = repmat(sin(th), 1, numSpatialBins*numSpatialBins) ;
xd = xd .* d(:)' ;
yd = yd .* d(:)' ;
% Re-arrange in sequential order the lines to draw
nans = NaN * ones(1,numSpatialBins^2*numOrientationBins) ;
x1 = xc(:)' ;
y1 = yc(:)' ;
x2 = x1 + xd ;
y2 = y1 + yd ;
xstars = [x1;x2;nans] ;
ystars = [y1;y2;nans] ;
% Horizontal lines of the grid
nans = NaN * ones(1,numSpatialBins+1);
xh = [x(:,1)' ; x(:,end)' ; nans] ;
yh = [y(:,1)' ; y(:,end)' ; nans] ;
% Verical lines of the grid
xv = [x(1,:) ; x(end,:) ; nans] ;
yv = [y(1,:) ; y(end,:) ; nans] ;
x=[xstars(:)' xh(:)' xv(:)'] ;
y=[ystars(:)' yh(:)' yv(:)'] ;
|
github
|
sabbiu/ObjectDetection-master
|
phow_caltech101.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/apps/phow_caltech101.m
| 11,594 |
utf_8
|
7f4890a2e6844ca56debbfe23cca64f3
|
function phow_caltech101()
% PHOW_CALTECH101 Image classification in the Caltech-101 dataset
% This program demonstrates how to use VLFeat to construct an image
% classifier on the Caltech-101 data. The classifier uses PHOW
% features (dense SIFT), spatial histograms of visual words, and a
% Chi2 SVM. To speedup computation it uses VLFeat fast dense SIFT,
% kd-trees, and homogeneous kernel map. The program also
% demonstrates VLFeat PEGASOS SVM solver, although for this small
% dataset other solvers such as LIBLINEAR can be more efficient.
%
% By default 15 training images are used, which should result in
% about 64% performance (a good performance considering that only a
% single feature type is being used).
%
% Call PHOW_CALTECH101 to train and test a classifier on a small
% subset of the Caltech-101 data. Note that the program
% automatically downloads a copy of the Caltech-101 data from the
% Internet if it cannot find a local copy.
%
% Edit the PHOW_CALTECH101 file to change the program configuration.
%
% To run on the entire dataset change CONF.TINYPROBLEM to FALSE.
%
% The Caltech-101 data is saved into CONF.CALDIR, which defaults to
% 'data/caltech-101'. Change this path to the desired location, for
% instance to point to an existing copy of the Caltech-101 data.
%
% The program can also be used to train a model on custom data by
% pointing CONF.CALDIR to it. Just create a subdirectory for each
% class and put the training images there. Make sure to adjust
% CONF.NUMTRAIN accordingly.
%
% Intermediate files are stored in the directory CONF.DATADIR. All
% such files begin with the prefix CONF.PREFIX, which can be changed
% to test different parameter settings without overriding previous
% results.
%
% The program saves the trained model in
% <CONF.DATADIR>/<CONF.PREFIX>-model.mat. This model can be used to
% test novel images independently of the Caltech data.
%
% load('data/baseline-model.mat') ; # change to the model path
% label = model.classify(model, im) ;
%
% Author: Andrea Vedaldi
% Copyright (C) 2011-2013 Andrea Vedaldi
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
conf.calDir = 'data/caltech-101' ;
conf.dataDir = 'data/' ;
conf.autoDownloadData = true ;
conf.numTrain = 15 ;
conf.numTest = 15 ;
conf.numClasses = 102 ;
conf.numWords = 600 ;
conf.numSpatialX = [2 4] ;
conf.numSpatialY = [2 4] ;
conf.quantizer = 'kdtree' ;
conf.svm.C = 10 ;
conf.svm.solver = 'sdca' ;
%conf.svm.solver = 'sgd' ;
%conf.svm.solver = 'liblinear' ;
conf.svm.biasMultiplier = 1 ;
conf.phowOpts = {'Step', 3} ;
conf.clobber = false ;
conf.tinyProblem = true ;
conf.prefix = 'baseline' ;
conf.randSeed = 1 ;
if conf.tinyProblem
conf.prefix = 'tiny' ;
conf.numClasses = 5 ;
conf.numSpatialX = 2 ;
conf.numSpatialY = 2 ;
conf.numWords = 300 ;
conf.phowOpts = {'Verbose', 2, 'Sizes', 7, 'Step', 5} ;
end
conf.vocabPath = fullfile(conf.dataDir, [conf.prefix '-vocab.mat']) ;
conf.histPath = fullfile(conf.dataDir, [conf.prefix '-hists.mat']) ;
conf.modelPath = fullfile(conf.dataDir, [conf.prefix '-model.mat']) ;
conf.resultPath = fullfile(conf.dataDir, [conf.prefix '-result']) ;
randn('state',conf.randSeed) ;
rand('state',conf.randSeed) ;
vl_twister('state',conf.randSeed) ;
% --------------------------------------------------------------------
% Download Caltech-101 data
% --------------------------------------------------------------------
if ~exist(conf.calDir, 'dir') || ...
(~exist(fullfile(conf.calDir, 'airplanes'),'dir') && ...
~exist(fullfile(conf.calDir, '101_ObjectCategories', 'airplanes')))
if ~conf.autoDownloadData
error(...
['Caltech-101 data not found. ' ...
'Set conf.autoDownloadData=true to download the required data.']) ;
end
vl_xmkdir(conf.calDir) ;
calUrl = ['http://www.vision.caltech.edu/Image_Datasets/' ...
'Caltech101/101_ObjectCategories.tar.gz'] ;
fprintf('Downloading Caltech-101 data to ''%s''. This will take a while.', conf.calDir) ;
untar(calUrl, conf.calDir) ;
end
if ~exist(fullfile(conf.calDir, 'airplanes'),'dir')
conf.calDir = fullfile(conf.calDir, '101_ObjectCategories') ;
end
% --------------------------------------------------------------------
% Setup data
% --------------------------------------------------------------------
classes = dir(conf.calDir) ;
classes = classes([classes.isdir]) ;
classes = {classes(3:conf.numClasses+2).name} ;
images = {} ;
imageClass = {} ;
for ci = 1:length(classes)
ims = dir(fullfile(conf.calDir, classes{ci}, '*.jpg'))' ;
ims = vl_colsubset(ims, conf.numTrain + conf.numTest) ;
ims = cellfun(@(x)fullfile(classes{ci},x),{ims.name},'UniformOutput',false) ;
images = {images{:}, ims{:}} ;
imageClass{end+1} = ci * ones(1,length(ims)) ;
end
selTrain = find(mod(0:length(images)-1, conf.numTrain+conf.numTest) < conf.numTrain) ;
selTest = setdiff(1:length(images), selTrain) ;
imageClass = cat(2, imageClass{:}) ;
model.classes = classes ;
model.phowOpts = conf.phowOpts ;
model.numSpatialX = conf.numSpatialX ;
model.numSpatialY = conf.numSpatialY ;
model.quantizer = conf.quantizer ;
model.vocab = [] ;
model.w = [] ;
model.b = [] ;
model.classify = @classify ;
% --------------------------------------------------------------------
% Train vocabulary
% --------------------------------------------------------------------
if ~exist(conf.vocabPath) || conf.clobber
% Get some PHOW descriptors to train the dictionary
selTrainFeats = vl_colsubset(selTrain, 30) ;
descrs = {} ;
%for ii = 1:length(selTrainFeats)
parfor ii = 1:length(selTrainFeats)
im = imread(fullfile(conf.calDir, images{selTrainFeats(ii)})) ;
im = standarizeImage(im) ;
[drop, descrs{ii}] = vl_phow(im, model.phowOpts{:}) ;
end
descrs = vl_colsubset(cat(2, descrs{:}), 10e4) ;
descrs = single(descrs) ;
% Quantize the descriptors to get the visual words
vocab = vl_kmeans(descrs, conf.numWords, 'verbose', 'algorithm', 'elkan', 'MaxNumIterations', 50) ;
save(conf.vocabPath, 'vocab') ;
else
load(conf.vocabPath) ;
end
model.vocab = vocab ;
if strcmp(model.quantizer, 'kdtree')
model.kdtree = vl_kdtreebuild(vocab) ;
end
% --------------------------------------------------------------------
% Compute spatial histograms
% --------------------------------------------------------------------
if ~exist(conf.histPath) || conf.clobber
hists = {} ;
parfor ii = 1:length(images)
% for ii = 1:length(images)
fprintf('Processing %s (%.2f %%)\n', images{ii}, 100 * ii / length(images)) ;
im = imread(fullfile(conf.calDir, images{ii})) ;
hists{ii} = getImageDescriptor(model, im);
end
hists = cat(2, hists{:}) ;
save(conf.histPath, 'hists') ;
else
load(conf.histPath) ;
end
% --------------------------------------------------------------------
% Compute feature map
% --------------------------------------------------------------------
psix = vl_homkermap(hists, 1, 'kchi2', 'gamma', .5) ;
% --------------------------------------------------------------------
% Train SVM
% --------------------------------------------------------------------
if ~exist(conf.modelPath) || conf.clobber
switch conf.svm.solver
case {'sgd', 'sdca'}
lambda = 1 / (conf.svm.C * length(selTrain)) ;
w = [] ;
parfor ci = 1:length(classes)
perm = randperm(length(selTrain)) ;
fprintf('Training model for class %s\n', classes{ci}) ;
y = 2 * (imageClass(selTrain) == ci) - 1 ;
[w(:,ci) b(ci) info] = vl_svmtrain(psix(:, selTrain(perm)), y(perm), lambda, ...
'Solver', conf.svm.solver, ...
'MaxNumIterations', 50/lambda, ...
'BiasMultiplier', conf.svm.biasMultiplier, ...
'Epsilon', 1e-3);
end
case 'liblinear'
svm = train(imageClass(selTrain)', ...
sparse(double(psix(:,selTrain))), ...
sprintf(' -s 3 -B %f -c %f', ...
conf.svm.biasMultiplier, conf.svm.C), ...
'col') ;
w = svm.w(:,1:end-1)' ;
b = svm.w(:,end)' ;
end
model.b = conf.svm.biasMultiplier * b ;
model.w = w ;
save(conf.modelPath, 'model') ;
else
load(conf.modelPath) ;
end
% --------------------------------------------------------------------
% Test SVM and evaluate
% --------------------------------------------------------------------
% Estimate the class of the test images
scores = model.w' * psix + model.b' * ones(1,size(psix,2)) ;
[drop, imageEstClass] = max(scores, [], 1) ;
% Compute the confusion matrix
idx = sub2ind([length(classes), length(classes)], ...
imageClass(selTest), imageEstClass(selTest)) ;
confus = zeros(length(classes)) ;
confus = vl_binsum(confus, ones(size(idx)), idx) ;
% Plots
figure(1) ; clf;
subplot(1,2,1) ;
imagesc(scores(:,[selTrain selTest])) ; title('Scores') ;
set(gca, 'ytick', 1:length(classes), 'yticklabel', classes) ;
subplot(1,2,2) ;
imagesc(confus) ;
title(sprintf('Confusion matrix (%.2f %% accuracy)', ...
100 * mean(diag(confus)/conf.numTest) )) ;
print('-depsc2', [conf.resultPath '.ps']) ;
save([conf.resultPath '.mat'], 'confus', 'conf') ;
% -------------------------------------------------------------------------
function im = standarizeImage(im)
% -------------------------------------------------------------------------
im = im2single(im) ;
if size(im,1) > 480, im = imresize(im, [480 NaN]) ; end
% -------------------------------------------------------------------------
function hist = getImageDescriptor(model, im)
% -------------------------------------------------------------------------
im = standarizeImage(im) ;
width = size(im,2) ;
height = size(im,1) ;
numWords = size(model.vocab, 2) ;
% get PHOW features
[frames, descrs] = vl_phow(im, model.phowOpts{:}) ;
% quantize local descriptors into visual words
switch model.quantizer
case 'vq'
[drop, binsa] = min(vl_alldist(model.vocab, single(descrs)), [], 1) ;
case 'kdtree'
binsa = double(vl_kdtreequery(model.kdtree, model.vocab, ...
single(descrs), ...
'MaxComparisons', 50)) ;
end
for i = 1:length(model.numSpatialX)
binsx = vl_binsearch(linspace(1,width,model.numSpatialX(i)+1), frames(1,:)) ;
binsy = vl_binsearch(linspace(1,height,model.numSpatialY(i)+1), frames(2,:)) ;
% combined quantization
bins = sub2ind([model.numSpatialY(i), model.numSpatialX(i), numWords], ...
binsy,binsx,binsa) ;
hist = zeros(model.numSpatialY(i) * model.numSpatialX(i) * numWords, 1) ;
hist = vl_binsum(hist, ones(size(bins)), bins) ;
hists{i} = single(hist / sum(hist)) ;
end
hist = cat(1,hists{:}) ;
hist = hist / sum(hist) ;
% -------------------------------------------------------------------------
function [className, score] = classify(model, im)
% -------------------------------------------------------------------------
hist = getImageDescriptor(model, im) ;
psix = vl_homkermap(hist, 1, 'kchi2', 'gamma', .5) ;
scores = model.w' * psix + model.b' ;
[score, best] = max(scores) ;
className = model.classes{best} ;
|
github
|
sabbiu/ObjectDetection-master
|
sift_mosaic.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/apps/sift_mosaic.m
| 4,621 |
utf_8
|
8fa3ad91b401b8f2400fb65944c79712
|
function mosaic = sift_mosaic(im1, im2)
% SIFT_MOSAIC Demonstrates matching two images using SIFT and RANSAC
%
% SIFT_MOSAIC demonstrates matching two images based on SIFT
% features and RANSAC and computing their mosaic.
%
% SIFT_MOSAIC by itself runs the algorithm on two standard test
% images. Use SIFT_MOSAIC(IM1,IM2) to compute the mosaic of two
% custom images IM1 and IM2.
% AUTORIGHTS
if nargin == 0
im1 = imread(fullfile(vl_root, 'data', 'river1.jpg')) ;
im2 = imread(fullfile(vl_root, 'data', 'river2.jpg')) ;
end
% make single
im1 = im2single(im1) ;
im2 = im2single(im2) ;
% make grayscale
if size(im1,3) > 1, im1g = rgb2gray(im1) ; else im1g = im1 ; end
if size(im2,3) > 1, im2g = rgb2gray(im2) ; else im2g = im2 ; end
% --------------------------------------------------------------------
% SIFT matches
% --------------------------------------------------------------------
[f1,d1] = vl_sift(im1g) ;
[f2,d2] = vl_sift(im2g) ;
[matches, scores] = vl_ubcmatch(d1,d2) ;
numMatches = size(matches,2) ;
X1 = f1(1:2,matches(1,:)) ; X1(3,:) = 1 ;
X2 = f2(1:2,matches(2,:)) ; X2(3,:) = 1 ;
% --------------------------------------------------------------------
% RANSAC with homography model
% --------------------------------------------------------------------
clear H score ok ;
for t = 1:100
% estimate homograpyh
subset = vl_colsubset(1:numMatches, 4) ;
A = [] ;
for i = subset
A = cat(1, A, kron(X1(:,i)', vl_hat(X2(:,i)))) ;
end
[U,S,V] = svd(A) ;
H{t} = reshape(V(:,9),3,3) ;
% score homography
X2_ = H{t} * X1 ;
du = X2_(1,:)./X2_(3,:) - X2(1,:)./X2(3,:) ;
dv = X2_(2,:)./X2_(3,:) - X2(2,:)./X2(3,:) ;
ok{t} = (du.*du + dv.*dv) < 6*6 ;
score(t) = sum(ok{t}) ;
end
[score, best] = max(score) ;
H = H{best} ;
ok = ok{best} ;
% --------------------------------------------------------------------
% Optional refinement
% --------------------------------------------------------------------
function err = residual(H)
u = H(1) * X1(1,ok) + H(4) * X1(2,ok) + H(7) ;
v = H(2) * X1(1,ok) + H(5) * X1(2,ok) + H(8) ;
d = H(3) * X1(1,ok) + H(6) * X1(2,ok) + 1 ;
du = X2(1,ok) - u ./ d ;
dv = X2(2,ok) - v ./ d ;
err = sum(du.*du + dv.*dv) ;
end
if exist('fminsearch') == 2
H = H / H(3,3) ;
opts = optimset('Display', 'none', 'TolFun', 1e-8, 'TolX', 1e-8) ;
H(1:8) = fminsearch(@residual, H(1:8)', opts) ;
else
warning('Refinement disabled as fminsearch was not found.') ;
end
% --------------------------------------------------------------------
% Show matches
% --------------------------------------------------------------------
dh1 = max(size(im2,1)-size(im1,1),0) ;
dh2 = max(size(im1,1)-size(im2,1),0) ;
figure(1) ; clf ;
subplot(2,1,1) ;
imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ;
o = size(im1,2) ;
line([f1(1,matches(1,:));f2(1,matches(2,:))+o], ...
[f1(2,matches(1,:));f2(2,matches(2,:))]) ;
title(sprintf('%d tentative matches', numMatches)) ;
axis image off ;
subplot(2,1,2) ;
imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ;
o = size(im1,2) ;
line([f1(1,matches(1,ok));f2(1,matches(2,ok))+o], ...
[f1(2,matches(1,ok));f2(2,matches(2,ok))]) ;
title(sprintf('%d (%.2f%%) inliner matches out of %d', ...
sum(ok), ...
100*sum(ok)/numMatches, ...
numMatches)) ;
axis image off ;
drawnow ;
% --------------------------------------------------------------------
% Mosaic
% --------------------------------------------------------------------
box2 = [1 size(im2,2) size(im2,2) 1 ;
1 1 size(im2,1) size(im2,1) ;
1 1 1 1 ] ;
box2_ = inv(H) * box2 ;
box2_(1,:) = box2_(1,:) ./ box2_(3,:) ;
box2_(2,:) = box2_(2,:) ./ box2_(3,:) ;
ur = min([1 box2_(1,:)]):max([size(im1,2) box2_(1,:)]) ;
vr = min([1 box2_(2,:)]):max([size(im1,1) box2_(2,:)]) ;
[u,v] = meshgrid(ur,vr) ;
im1_ = vl_imwbackward(im2double(im1),u,v) ;
z_ = H(3,1) * u + H(3,2) * v + H(3,3) ;
u_ = (H(1,1) * u + H(1,2) * v + H(1,3)) ./ z_ ;
v_ = (H(2,1) * u + H(2,2) * v + H(2,3)) ./ z_ ;
im2_ = vl_imwbackward(im2double(im2),u_,v_) ;
mass = ~isnan(im1_) + ~isnan(im2_) ;
im1_(isnan(im1_)) = 0 ;
im2_(isnan(im2_)) = 0 ;
mosaic = (im1_ + im2_) ./ mass ;
figure(2) ; clf ;
imagesc(mosaic) ; axis image off ;
title('Mosaic') ;
if nargout == 0, clear mosaic ; end
end
|
github
|
sabbiu/ObjectDetection-master
|
encodeImage.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/apps/recognition/encodeImage.m
| 5,278 |
utf_8
|
5d9dc6161995b8e10366b5649bf4fda4
|
function descrs = encodeImage(encoder, im, varargin)
% ENCODEIMAGE Apply an encoder to an image
% DESCRS = ENCODEIMAGE(ENCODER, IM) applies the ENCODER
% to image IM, returning a corresponding code vector PSI.
%
% IM can be an image, the path to an image, or a cell array of
% the same, to operate on multiple images.
%
% ENCODEIMAGE(ENCODER, IM, CACHE) utilizes the specified CACHE
% directory to store encodings for the given images. The cache
% is used only if the images are specified as file names.
%
% See also: TRAINENCODER().
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.cacheDir = [] ;
opts.cacheChunkSize = 512 ;
opts = vl_argparse(opts,varargin) ;
if ~iscell(im), im = {im} ; end
% break the computation into cached chunks
startTime = tic ;
descrs = cell(1, numel(im)) ;
numChunks = ceil(numel(im) / opts.cacheChunkSize) ;
for c = 1:numChunks
n = min(opts.cacheChunkSize, numel(im) - (c-1)*opts.cacheChunkSize) ;
chunkPath = fullfile(opts.cacheDir, sprintf('chunk-%03d.mat',c)) ;
if ~isempty(opts.cacheDir) && exist(chunkPath)
fprintf('%s: loading descriptors from %s\n', mfilename, chunkPath) ;
load(chunkPath, 'data') ;
else
range = (c-1)*opts.cacheChunkSize + (1:n) ;
fprintf('%s: processing a chunk of %d images (%3d of %3d, %5.1fs to go)\n', ...
mfilename, numel(range), ...
c, numChunks, toc(startTime) / (c - 1) * (numChunks - c + 1)) ;
data = processChunk(encoder, im(range)) ;
if ~isempty(opts.cacheDir)
save(chunkPath, 'data') ;
end
end
descrs{c} = data ;
clear data ;
end
descrs = cat(2,descrs{:}) ;
% --------------------------------------------------------------------
function psi = processChunk(encoder, im)
% --------------------------------------------------------------------
psi = cell(1,numel(im)) ;
if numel(im) > 1 & matlabpool('size') > 1
parfor i = 1:numel(im)
psi{i} = encodeOne(encoder, im{i}) ;
end
else
% avoiding parfor makes debugging easier
for i = 1:numel(im)
psi{i} = encodeOne(encoder, im{i}) ;
end
end
psi = cat(2, psi{:}) ;
% --------------------------------------------------------------------
function psi = encodeOne(encoder, im)
% --------------------------------------------------------------------
im = encoder.readImageFn(im) ;
features = encoder.extractorFn(im) ;
imageSize = size(im) ;
psi = {} ;
for i = 1:size(encoder.subdivisions,2)
minx = encoder.subdivisions(1,i) * imageSize(2) ;
miny = encoder.subdivisions(2,i) * imageSize(1) ;
maxx = encoder.subdivisions(3,i) * imageSize(2) ;
maxy = encoder.subdivisions(4,i) * imageSize(1) ;
ok = ...
minx <= features.frame(1,:) & features.frame(1,:) < maxx & ...
miny <= features.frame(2,:) & features.frame(2,:) < maxy ;
descrs = encoder.projection * bsxfun(@minus, ...
features.descr(:,ok), ...
encoder.projectionCenter) ;
if encoder.renormalize
descrs = bsxfun(@times, descrs, 1./max(1e-12, sqrt(sum(descrs.^2)))) ;
end
w = size(im,2) ;
h = size(im,1) ;
frames = features.frame(1:2,:) ;
frames = bsxfun(@times, bsxfun(@minus, frames, [w;h]/2), 1./[w;h]) ;
descrs = extendDescriptorsWithGeometry(encoder.geometricExtension, frames, descrs) ;
switch encoder.type
case 'bovw'
[words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ...
descrs, ...
'MaxComparisons', 100) ;
z = vl_binsum(zeros(encoder.numWords,1), 1, double(words)) ;
z = sqrt(z) ;
case 'fv'
z = vl_fisher(descrs, ...
encoder.means, ...
encoder.covariances, ...
encoder.priors, ...
'Improved') ;
case 'vlad'
[words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ...
descrs, ...
'MaxComparisons', 15) ;
assign = zeros(encoder.numWords, numel(words), 'single') ;
assign(sub2ind(size(assign), double(words), 1:numel(words))) = 1 ;
z = vl_vlad(descrs, ...
encoder.words, ...
assign, ...
'SquareRoot', ...
'NormalizeComponents') ;
end
z = z / max(sqrt(sum(z.^2)), 1e-12) ;
psi{i} = z(:) ;
end
psi = cat(1, psi{:}) ;
% --------------------------------------------------------------------
function psi = getFromCache(name, cache)
% --------------------------------------------------------------------
[drop, name] = fileparts(name) ;
cachePath = fullfile(cache, [name '.mat']) ;
if exist(cachePath, 'file')
data = load(cachePath) ;
psi = data.psi ;
else
psi = [] ;
end
% --------------------------------------------------------------------
function storeToCache(name, cache, psi)
% --------------------------------------------------------------------
[drop, name] = fileparts(name) ;
cachePath = fullfile(cache, [name '.mat']) ;
vl_xmkdir(cache) ;
data.psi = psi ;
save(cachePath, '-STRUCT', 'data') ;
|
github
|
sabbiu/ObjectDetection-master
|
experiments.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/apps/recognition/experiments.m
| 6,905 |
utf_8
|
1e4a4911eed4a451b9488b9e6cc9b39c
|
function experiments()
% EXPERIMENTS Run image classification experiments
% The experimens download a number of benchmark datasets in the
% 'data/' subfolder. Make sure that there are several GBs of
% space available.
%
% By default, experiments run with a lite option turned on. This
% quickly runs all of them on tiny subsets of the actual data.
% This is used only for testing; to run the actual experiments,
% set the lite variable to false.
%
% Running all the experiments is a slow process. Using parallel
% MATLAB and several cores/machiens is suggested.
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
lite = true ;
clear ex ;
ex(1).prefix = 'fv-aug' ;
ex(1).trainOpts = {'C', 10} ;
ex(1).datasets = {'fmd', 'scene67'} ;
ex(1).seed = 1 ;
ex(1).opts = {...
'type', 'fv', ...
'numWords', 256, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'xy', ...
'numPcaDimensions', 80, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(2) = ex(1) ;
ex(2).datasets = {'caltech101'} ;
ex(2).opts{end} = @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(0:-.5:-3)) ;
ex(3) = ex(1) ;
ex(3).datasets = {'voc07'} ;
ex(3).C = 1 ;
ex(4) = ex(1) ;
ex(4).prefix = 'vlad-aug' ;
ex(4).opts = {...
'type', 'vlad', ...
'numWords', 256, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'xy', ...
'numPcaDimensions', 100, ...
'whitening', true, ...
'whiteningRegul', 0.01, ...
'renormalize', true, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(5) = ex(4) ;
ex(5).datasets = {'caltech101'} ;
ex(5).opts{end} = ex(2).opts{end} ;
ex(6) = ex(4) ;
ex(6).datasets = {'voc07'} ;
ex(6).C = 1 ;
ex(7) = ex(1) ;
ex(7).prefix = 'bovw-aug' ;
ex(7).opts = {...
'type', 'bovw', ...
'numWords', 4096, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'xy', ...
'numPcaDimensions', 100, ...
'whitening', true, ...
'whiteningRegul', 0.01, ...
'renormalize', true, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(8) = ex(7) ;
ex(8).datasets = {'caltech101'} ;
ex(8).opts{end} = ex(2).opts{end} ;
ex(9) = ex(7) ;
ex(9).datasets = {'voc07'} ;
ex(9).C = 1 ;
ex(10).prefix = 'fv' ;
ex(10).trainOpts = {'C', 10} ;
ex(10).datasets = {'fmd', 'scene67'} ;
ex(10).seed = 1 ;
ex(10).opts = {...
'type', 'fv', ...
'numWords', 256, ...
'layouts', {'1x1'}, ...
'geometricExtension', 'none', ...
'numPcaDimensions', 80, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(11) = ex(10) ;
ex(11).datasets = {'caltech101'} ;
ex(11).opts{end} = @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(0:-.5:-3)) ;
ex(12) = ex(10) ;
ex(12).datasets = {'voc07'} ;
ex(12).C = 1 ;
ex(13).prefix = 'fv-sp' ;
ex(13).trainOpts = {'C', 10} ;
ex(13).datasets = {'fmd', 'scene67'} ;
ex(13).seed = 1 ;
ex(13).opts = {...
'type', 'fv', ...
'numWords', 256, ...
'layouts', {'1x1', '3x1'}, ...
'geometricExtension', 'none', ...
'numPcaDimensions', 80, ...
'extractorFn', @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(1:-.5:-3))};
ex(14) = ex(13) ;
ex(14).datasets = {'caltech101'} ;
ex(14).opts{6} = {'1x1', '2x2'} ;
ex(14).opts{end} = @(x) getDenseSIFT(x, ...
'step', 4, ...
'scales', 2.^(0:-.5:-3)) ;
ex(15) = ex(13) ;
ex(15).datasets = {'voc07'} ;
ex(15).C = 1 ;
if lite, tag = 'lite' ;
else, tag = 'ex' ; end
for i=1:numel(ex)
for j=1:numel(ex(i).datasets)
dataset = ex(i).datasets{j} ;
if ~isfield(ex(i), 'trainOpts') || ~iscell(ex(i).trainOpts)
ex(i).trainOpts = {} ;
end
traintest(...
'prefix', [tag '-' dataset '-' ex(i).prefix], ...
'seed', ex(i).seed, ...
'dataset', char(dataset), ...
'datasetDir', fullfile('data', dataset), ...
'lite', lite, ...
ex(i).trainOpts{:}, ...
'encoderParams', ex(i).opts) ;
end
end
% print HTML table
pf('<table>\n') ;
ph('method', 'VOC07', 'Caltech 101', 'Scene 67', 'FMD') ;
pr('FV', ...
ge([tag '-voc07-fv'],'ap11'), ...
ge([tag '-caltech101-fv']), ...
ge([tag '-scene67-fv']), ...
ge([tag '-fmd-fv'])) ;
pr('FV + aug.', ...
ge([tag '-voc07-fv-aug'],'ap11'), ...
ge([tag '-caltech101-fv-aug']), ...
ge([tag '-scene67-fv-aug']), ...
ge([tag '-fmd-fv-aug'])) ;
pr('FV + s.p.', ...
ge([tag '-voc07-fv-sp'],'ap11'), ...
ge([tag '-caltech101-fv-sp']), ...
ge([tag '-scene67-fv-sp']), ...
ge([tag '-fmd-fv-sp'])) ;
%pr('VLAD', ...
% ge([tag '-voc07-vlad'],'ap11'), ...
% ge([tag '-caltech101-vlad']), ...
% ge([tag '-scene67-vlad']), ...
% ge([tag '-fmd-vlad'])) ;
pr('VLAD + aug.', ...
ge([tag '-voc07-vlad-aug'],'ap11'), ...
ge([tag '-caltech101-vlad-aug']), ...
ge([tag '-scene67-vlad-aug']), ...
ge([tag '-fmd-vlad-aug'])) ;
%pr('VLAD+sp', ...
% ge([tag '-voc07-vlad-sp'],'ap11'), ...
% ge([tag '-caltech101-vlad-sp']), ...
% ge([tag '-scene67-vlad-sp']), ...
% ge([tag '-fmd-vlad-sp'])) ;
%pr('BOVW', ...
% ge([tag '-voc07-bovw'],'ap11'), ...
% ge([tag '-caltech101-bovw']), ...
% ge([tag '-scene67-bovw']), ...
% ge([tag '-fmd-bovw'])) ;
pr('BOVW + aug.', ...
ge([tag '-voc07-bovw-aug'],'ap11'), ...
ge([tag '-caltech101-bovw-aug']), ...
ge([tag '-scene67-bovw-aug']), ...
ge([tag '-fmd-bovw-aug'])) ;
%pr('BOVW+sp', ...
% ge([tag '-voc07-bovw-sp'],'ap11'), ...
% ge([tag '-caltech101-bovw-sp']), ...
% ge([tag '-scene67-bovw-sp']), ...
% ge([tag '-fmd-bovw-sp'])) ;
pf('</table>\n');
function pf(str)
fprintf(str) ;
function str = ge(name, format)
if nargin == 1, format = 'acc'; end
data = load(fullfile('data', name, 'result.mat')) ;
switch format
case 'acc'
str = sprintf('%.2f%% <span style="font-size:8px;">Acc</span>', mean(diag(data.confusion)) * 100) ;
case 'ap11'
str = sprintf('%.2f%% <span style="font-size:8px;">mAP</span>', mean(data.ap11) * 100) ;
end
function pr(varargin)
fprintf('<tr>') ;
for i=1:numel(varargin), fprintf('<td>%s</td>',varargin{i}) ; end
fprintf('</tr>\n') ;
function ph(varargin)
fprintf('<tr>') ;
for i=1:numel(varargin), fprintf('<th>%s</th>',varargin{i}) ; end
fprintf('</tr>\n') ;
|
github
|
sabbiu/ObjectDetection-master
|
getDenseSIFT.m
|
.m
|
ObjectDetection-master/Project-CLI/vlfeat-0.9.20/apps/recognition/getDenseSIFT.m
| 1,679 |
utf_8
|
2059c0a2a4e762226d89121408c6e51c
|
function features = getDenseSIFT(im, varargin)
% GETDENSESIFT Extract dense SIFT features
% FEATURES = GETDENSESIFT(IM) extract dense SIFT features from
% image IM.
% Author: Andrea Vedaldi
% Copyright (C) 2013 Andrea Vedaldi
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.scales = logspace(log10(1), log10(.25), 5) ;
opts.contrastthreshold = 0 ;
opts.step = 3 ;
opts.rootSift = false ;
opts.normalizeSift = true ;
opts.binSize = 8 ;
opts.geometry = [4 4 8] ;
opts.sigma = 0 ;
opts = vl_argparse(opts, varargin) ;
dsiftOpts = {'norm', 'fast', 'floatdescriptors', ...
'step', opts.step, ...
'size', opts.binSize, ...
'geometry', opts.geometry} ;
if size(im,3)>1, im = rgb2gray(im) ; end
im = im2single(im) ;
im = vl_imsmooth(im, opts.sigma) ;
for si = 1:numel(opts.scales)
im_ = imresize(im, opts.scales(si)) ;
[frames{si}, descrs{si}] = vl_dsift(im_, dsiftOpts{:}) ;
% root SIFT
if opts.rootSift
descrs{si} = sqrt(descrs{si}) ;
end
if opts.normalizeSift
descrs{si} = snorm(descrs{si}) ;
end
% zero low contrast descriptors
info.contrast{si} = frames{si}(3,:) ;
kill = info.contrast{si} < opts.contrastthreshold ;
descrs{si}(:,kill) = 0 ;
% store frames
frames{si}(1:2,:) = (frames{si}(1:2,:)-1) / opts.scales(si) + 1 ;
frames{si}(3,:) = opts.binSize / opts.scales(si) / 3 ;
end
features.frame = cat(2, frames{:}) ;
features.descr = cat(2, descrs{:}) ;
features.contrast = cat(2, info.contrast{:}) ;
function x = snorm(x)
x = bsxfun(@times, x, 1./max(1e-5,sqrt(sum(x.^2,1)))) ;
|
github
|
neuropoly/axonpacking-master
|
axons_setup.m
|
.m
|
axonpacking-master/code/axons_setup.m
| 2,927 |
utf_8
|
b9f1c3bdbc776d4043dbc9a4d1e11512
|
function [D,x0, side] = axons_setup(axons, lawname, k)
% author : Tom Mingasson
% axonsSetup creates a randomly generated axon gamma or lognormal distribution and initilialize axons positions in a square area defined by its length 'side'.
% diameters distribution under a gamma or lognormal law
D = samplingHastingsMetropolis(axons, lawname, k);
% dimension of the square area
N = axons.N{k};
if axons.d_var{k} == 0
side = sqrt(N*(3*max(D(:))+axons.Delta{k}).^2);
else
side = sqrt(N*(2*max(D(:))+axons.Delta{k}).^2);
end
% Random positions on a grid for the N axons
sqrt_N = round(sqrt(N))+1;
[Xgrid Ygrid] = meshgrid(1:side/sqrt_N:side, 1:side/sqrt_N:side);
Xgrid =Xgrid(:);
Ygrid =Ygrid(:);
Permutations = randperm(sqrt_N^2);
x0 = zeros(N,2);
for i=1:N
x0(i,:) = [Xgrid(Permutations(i)) Ygrid(Permutations(i))];
end
x0 = reshape(x0',1,2*N)';
end
function d = samplingHastingsMetropolis(axons,lawName,k)
sigma_instru = 1;
N = axons.N{k};
x = zeros(N,1);
x(1)=axons.d_mean{k};
xmin = axons.threshold_low{k};
xmax = axons.threshold_high{k};
axe_hist =linspace(xmin,xmax,100);
for n=1:N-1
% drawing of x* from x(n) (= current point) under a gaussian intrumental law
x_star = x(n) + sigma_instru*randn;
% acceptation or reject
proba_accept = (q_instru(x(n),x_star,sigma_instru)*pobj(x_star,axons,lawName,k))/(q_instru(x_star,x(n),sigma_instru)*pobj(x(n),axons,lawName,k));
u=rand;
if u<proba_accept
x(n+1)=x_star;
else
x(n+1)=x(n);
end
end
figure('Name','Disk diameter histogram')
hold off
xth = linspace(0.01,xmax,1000);
yth = pobj(xth, axons,lawName, k);
[n_hist,bins]=hist(x(1:n),axe_hist);
h = bar(bins,n_hist);
set(h,'barwidth',0.5)
hold on
plot(xth,yth/max(yth(:))*max(n_hist),'r', 'LineWidth',1 )
legend('histogram',['distribution law : ', lawName])
drawnow
xlabel('diameters (um)')
ylabel('number of disks')
d = x;
end
function [ pobj ] = pobj(x, axons,lawName, k)
% Probability pobj(x) where pobj is the function we want to sample
meanAxons = axons.d_mean{k};
varAxons = axons.d_var{k};
threshold_high = axons.threshold_high{k};
threshold_low = axons.threshold_low{k};
switch lawName
case 'lognormal'
mu = log(meanAxons) - 1/2*log(1 + varAxons/(meanAxons)^2);
sigma = sqrt( log( 1 + varAxons/(meanAxons)^2) );
if x>=threshold_high | x <= threshold_low
pobj=0;
else
pobj = lognpdf(x,mu,sigma);
end
case 'gamma'
a = meanAxons^2/varAxons;
b = varAxons/meanAxons;
if x>=threshold_high | x<=threshold_low
pobj=0;
else
pobj = gampdf(x, a, b);
end
end
end
function [q] = q_instru( x_star, x_courant, sigma_instru )
% Evaluation of the instrumental function q for (x, x_current)
q = 1/(sigma_instru*sqrt(2*pi))*exp(-(x_star-x_courant)^2/(2*sigma_instru^2));
end
|
github
|
neuropoly/axonpacking-master
|
process_packing.m
|
.m
|
axonpacking-master/code/process_packing.m
| 5,704 |
utf_8
|
c917838799e34d0310385913bd8f51d2
|
function [final_positions, overlap, fvf_historic] = process_packing(x0, d, gap, side, iter_max, iter_fvf)
% author : Tom Mingasson
% function that create the packing i.e disk migrations from intial positions
disp(' ')
disp('Packing in process...')
disp(' ')
N = length(d);
fvf_historic = [];
x = x0;
progress = progressBar(iter_max);
for iter = 1:iter_max
MyGrad = compute_grad(x, d+gap/2, side);
x = x + MyGrad;
if round(iter/iter_fvf)==iter/iter_fvf | iter==1
pts = reshape(x,2,length(x)/2);
t = 0:.1:2*pi+0.1;
% FVF mask
resolution = 0.05; % um
masksize = ceil(side/resolution);
FVF_mask = false(masksize);
for id=1:N
Xfibers = d(id)*cos(t) + pts(1,id);
Yfibers = d(id)*sin(t) + pts(2,id);
FVF_mask = FVF_mask | poly2mask(Xfibers/side*masksize, Yfibers/side*masksize, masksize, masksize);
end
% AVF mask
AVF_mask = false(masksize);
g_ratio=compute_gratio(d);
for id=1:N
Xaxons = g_ratio(id)*d(id)*cos(t) + pts(1,id);
Yaxons = g_ratio(id)*d(id)*sin(t) + pts(2,id);
AVF_mask = AVF_mask | poly2mask(Xaxons/side*masksize, Yaxons/side*masksize, masksize, masksize);
end
% mask in which FVF is computed. Its area is Atot.
Ls = sqrt(sum(pi*(d+gap/2).^2))*(4/5)/side*masksize;
Atot = Ls * Ls;
Xmin = round(mean(pts(1,:))/side*masksize - Ls/2);
Xmax = round(mean(pts(1,:))/side*masksize + Ls/2);
Ymin = round(mean(pts(2,:))/side*masksize - Ls/2);
Ymax = round(mean(pts(2,:))/side*masksize + Ls/2);
FVF_mask_trunc = FVF_mask(Xmin:Xmax,Ymin:Ymax);
fvf_historic = [fvf_historic sum(FVF_mask_trunc(:))/ Atot];
% display intermediate packing and compute FVF
set(figure(201), 'Name', 'Disk migration'); clf
subplot(1,2,1)
colormap(gray)
imagesc(AVF_mask - FVF_mask)
axis off
hold on
rectangle('Position',[Xmin, Ymin, Ls, Ls],'EdgeColor', 'r', 'LineWidth', 1.5)
title(['Diam Mean : ',num2str(round(mean(d(:))*10)/10),' um ','Diam Var : ',num2str(round(var(d(:))*10)/10),' um ','Gap : ',num2str(gap),' um '],'FontSize',10,'FontWeight','bold');
axis square
subplot(1,2,2)
plot([1:length(fvf_historic)]*iter_fvf, fvf_historic, 'r*-')
title('Disk density in the red square' ,'FontSize',10,'FontWeight','bold');
axis square
drawnow
end
progress.update();
end
progress.close();
final_positions = reshape(x,2,length(x)/2);
% evaluate overlap in the final packing
overlap = 0;
for i = 1:N-1
for j = i+1:N
[~,~,area] = areaIntersect(final_positions(:,i),d(i),final_positions(:,j),d(j));
overlap = overlap + area;
end
end
disp(' ')
disp(['overlap area ratio regarding total disk areas in the packing: ', num2str(overlap / sum(pi*d.^2) * 100), ' %'])
end
function MyGrad = compute_grad(x, D, side)
% author : Tom Mingasson
Kcenter0 = 0.01; % center step coeff for disks withOUT overlapping
Kcenter1 = 0; % center step coeff for disks with overlapping
Krep = 0.1; % repulsion step coeff for disks with overlapping
pts = reshape(x,2,length(x)/2);
N=size(pts,2);
% intersection
P = squareform(pdist(pts','euclidean'))+eye(N);
Rsum = (repmat(D,1,N)' + repmat(D,1,N)).*(tril(ones(N,N),-1)+triu(ones(N,N),1));
L = (Rsum./P-1); % >0 if intersection
Lbin = L; Lbin(Lbin>0) = 1; Lbin(Lbin<=0) = 0; F = floor(linspace(1,N+1,2*N+1)); F=F(1:end-1); Lbin2 = Lbin(:,F);
inter1_index = repmat(sum(Lbin),2,1); inter1_index(inter1_index>0)=1; % disks that overlap
inter0_index = 1 - inter1_index; % disks that NOT overlap
% attraction
pts_centered = side/2-pts;
attraction_norm = sqrt(pts_centered(1,:).^2+pts_centered(2,:).^2);
attraction = pts_centered./repmat(attraction_norm,[2,1]);
% repulsion
U = repmat(x',N,1)-repmat(pts',1,N);
Usum = sum(U.*Lbin2,1);
Unorm = sqrt(Usum(1:2:end).^2 + Usum(2:2:end).^2); Unorm(Unorm==0) = 1;
Unormalization = repmat(Unorm,2,1); Unormalization = Unormalization(:)';
Usum_normed = Usum./Unormalization ;
repulsion = (Usum_normed.*inter1_index(:)')';
MyGrad = reshape(Kcenter0.*attraction.*inter0_index + Kcenter1.*attraction.*inter1_index,1,2*N)' + Krep.*repulsion;
end
function [p,q,areatotal,numberOfPoints] = areaIntersect(C1,r1,C2,r2)
% Circle centers C1 and C2 with radius r1 and r2.
% Compute x and y
% Solve in easy coordinates
a = norm(C1-C2);
% Check for divide by zero
if isequal(a,0)
% Circles have same center. Return the area of the smaller circle.
p = [NaN;NaN]; q = [NaN;NaN]; numberOfPoints = Inf;
areatotal = pi*min(r1,r2)^2;
return
end
x = 0.5*(a + (r1^2 - r2^2)/a);
if r1^2 < x^2 % Check for sqrt of negative
p = [NaN;NaN]; q = [NaN;NaN];
if r1 + r2 < a
areatotal = 0; numberOfPoints = 0;
else % One circle is inside the other
areatotal = pi*min(r1,r2)^2;
numberOfPoints = Inf;
end
return
end
y = sqrt(r1^2 - x^2);
% Original coordinates basis
i = (C2-C1)/norm(C2-C1);
j = null(i');
% Intersection points in original coordinates
p = C1 + i*x + j*y ;
q = C1 + i*x - j*y;
% Compute the angle theta between radius and x-axis
% in the easy coordinates
theta1 = atan2(y,x);
theta2 = atan2(y,a-x);
% Obtain A1 with x, y, r1
area1 = theta1*r1^2 - x*y;
% Obtain A2 with a-x, y, r2
area2 = theta2*r2^2 - (a-x)*y;
areatotal = area1 + area2;
if isequal(p,q)
numberOfPoints = 1;
else
numberOfPoints = 2;
end
end
|
github
|
domingomery/Balu-master
|
Bds_bootstrap.m
|
.m
|
Balu-master/DataSelectionAndGeneration/Bds_bootstrap.m
| 690 |
utf_8
|
ded2459781ccf06343c1b7ebfedea80b
|
% [Xb,db,Xnb,dnb] = Bds_bootstrap(X,d,N)
%
% Toolbox: Balu
%
% Bootstrap sample (with replacement)
%
% input: (X,d) means features and ideal classification
% Bbootsample takes a bootstrap sample of (X,d) to build (Xb,db).
% N is the number of samples of Xb, default is the number of samples
% of X.
% Xnb,dnb are the samples not considered in Xb,db.
%
% D.Mery, PUC-DCC, 2010
% http://dmery.ing.puc.cl
function [Xb,db,Xnb,dnb] = Bds_bootstrap(X,d,N)
Nx = size(X,1);
if not(exist('N','var'))
N = Nx;
end
ib = mod(ceil(N*rand(N,1)),Nx)+1;
Xb = X(ib,:);
db = d(ib,:);
Nx = size(X,1);
nb = ones(Nx,1);
nb(ib) = 0;
inb = find(nb==1);
Xnb = X(inb,:);
dnb = d(inb,:);
|
github
|
domingomery/Balu-master
|
Bds_smote.m
|
.m
|
Balu-master/DataSelectionAndGeneration/Bds_smote.m
| 3,500 |
utf_8
|
af43561c3a7f3af17d7ef3465ae1c7e2
|
% [New_X, New_d] = Bds_smote(X, d, smote_rate, k)
%
% Toolbox: Balu
%
% OVER-SAMPLING method, where the label for the majority class is 0
% and the label for the minority class is 1.
%
% This function implements SMOTE (Synthetic Minority Over-sampling TEchnique)
% an oversampling technique for imbalanced data sets, with two classes.
% The algorithm generates a synthetic sample as a point along the line
% between each minority sample and one random point selected of their
% K-NN in the same class.
%
% Input:
% X is a matrix with features (columns).
% d is the ideal classification for X.
% smote_rate is the rate of the synthetic samples to be created for
% the minority class. A value of 1.0 means that 100% of the data in
% the minority class will be generated.
% k is the number of neighbours to use
%
% Output:
% New_X is the new feature matrix augmented with the synthetic samples
% New_d is the new ideal classification for New_X.
%
% For more details on the theoretical description of the algorithm
% please refer to the following paper:
% Chawla, N. V. et al (2002). SMOTE: synthetic minority over-sampling
% technique in J. Arti?cial Intell. Res., vol. 16, n.o 1, pp. 321?357
%
% This implementation use the nearestneighbour provided by Richard
% Brown,available on:
% http://www.mathworks.com/matlabcentral/fileexchange/38830-smote-synthe
% tic-minority-over-sampling-technique
%
% C. Mera, UNAL, 2013
function [New_X, New_d] = Bds_smote(X, d, smote_rate, k)
if (nargin < 3)
smote_rate = 1.0;
k = 5;
elseif (nargin < 4)
k = 5;
end
if (smote_rate > 0)
% POS_DAT = candidate points of the minority class (labeled 1)
POS_DAT = X(d == 1,:);
POS_DAT = POS_DAT';
pos_size = size(POS_DAT, 2);
% Calculate the number N of synthetic data examples that need
% to be generated for the minority class
N = round(pos_size * smote_rate);
% If the rate es less than 1, only a random sample of the minority
% class is used
if (smote_rate < 1)
RND_IDX = randsample(pos_size, N);
POS_DAT = POS_DAT(:,RND_IDX);
pos_size = size(POS_DAT, 2);
end
% Finding the k nearest neighbours the positive points
I = nearestneighbour(POS_DAT, POS_DAT, 'NumberOfNeighbours', k+1);
I = I';
[r, c] = size(I);
Xn = ones(N,1);
XX = zeros(size(POS_DAT,1), N);
j = 1;
% If the rate is a multiple of 1
while (N >= pos_size)
for i = 1:r
index = I(i,randi(k)+1);
alpha = rand;
new_P = (1-alpha).*POS_DAT(:,i) + alpha.*(POS_DAT(:,index));
XX(:,j) = new_P;
N = N-1;
j = j+1;
end
end
% The remaning N synthetic samples to be created
while (N > 0)
i = randi(r);
index = I(i, randi(k)+1);
alpha = rand;
new_P = (1-alpha).*POS_DAT(:,i) + alpha.*(POS_DAT(:,index));
XX(:,j) = new_P;
N = N-1;
j = j+1;
end
New_X = [X; XX'];
New_d = [d; Xn];
else
New_X = X;
New_d = d;
end
end
|
github
|
domingomery/Balu-master
|
Bds_ixstratify.m
|
.m
|
Balu-master/DataSelectionAndGeneration/Bds_ixstratify.m
| 762 |
utf_8
|
6d0584ad85f7d3d3b0727f47cc3cb6e6
|
% [i1,i2] = Bds_ixstratify(d,s)
%
% Toolbox: Balu
%
% Data Stratification (without replacement)
%
% input: (d,s) ideal classification and portion
% Bds_sixtratify takes randomily a portion s (s between 0 and 1) of each class
% from d to build indices i1. The indices of not used samples are stored in i2.
%
% D.Mery, PUC-DCC, 2013
% http://dmery.ing.puc.cl
function [i1,i2] = Bds_ixstratify(d,s)
dmin = int8(min(d));
dmax = int8(max(d));
i1 = [];
i2 = [];
for k=dmin:dmax
ik = find(d==k);
dk = d(ik);
nk = length(dk);
rk = rand(nk,1);
[i,j] = sort(rk);
sk = ceil(s*nk);
if (sk>0)
i1 = [i1; ik(j(1:sk))];
end
if (sk<nk)
i2 = [i2; ik(j(sk+1:nk))];
end
end
|
github
|
domingomery/Balu-master
|
Bds_nostratify.m
|
.m
|
Balu-master/DataSelectionAndGeneration/Bds_nostratify.m
| 751 |
utf_8
|
594a7e2dc975c4df569b271f69f10e3e
|
% [X1,d1,X2,d2] = Bds_nostratify(X,d,s)
%
% Toolbox: Balu
%
% Data Sampling without Stratification (without replacement)
%
% input: (X,d) means features and ideal classification
% Bnostratify takes randomily a portion s (s between 0 and 1) of the
% whole that without considering the portion of each class
% from (X,d) to build (X1,d1). The samples not used in (X1,d1) are
% stored in (X2,d2).
%
% D.Mery, PUC-DCC, 2010
% http://dmery.ing.puc.cl
function [X1,d1,X2,d2] = Bds_nostratify(X,d,s)
N = size(X,1);
rn = rand(N,1);
[i,j] = sort(rn);
Xr = X(j,:);
dr = d(j);
r = fix(s*N);
R = [1 r;r+1 N];
X1 = Xr(R(1,1):R(1,2),:);
d1 = dr(R(1,1):R(1,2),:);
X2 = Xr(R(2,1):R(2,2),:);
d2 = dr(R(2,1):R(2,2),:);
|
github
|
domingomery/Balu-master
|
Bds_gaussgen.m
|
.m
|
Balu-master/DataSelectionAndGeneration/Bds_gaussgen.m
| 1,006 |
utf_8
|
8e1c348d753a5b1efba901c7fe3342de
|
% [X,d] = Bds_gaussgen(m,s,n)
%
% Toolbox: Balu
%
% Gaussian Random Sample Generator.
% m matrix qxp. m(i,j) is mean of class i for feature j
% s matrix qxp. s(i,j) is std of class i for feature j
% n vector qx1. n(i) is number of samples of class i
%
% Example for two classes and two features:
% [X,d] = Bds_gaussgen([10 1;1 10],4*ones(2,2),500*ones(2,1));
% Bio_plotfeatures(X,d)
%
% Example for three classes and two features:
% [X,d] = Bds_gaussgen([2 1;1 2;2 2],ones(3,2)/4,500*ones(3,1));
% Bio_plotfeatures(X,d)
%
% (c) GRIMA-DCCUC, 2011
% http://grima.ing.puc.cl
%
function [X,d] = Bds_gaussgen(m,s,n)
q = length(n); % number of classes
p = size(m,2); % number of features
N = sum(n); % number of samples
X = zeros(N,p);
d = zeros(N,1);
t = 1;
for i=1:q
d(t:t+n(i)-1) = i;
x = zeros(n(i),p);
for j=1:p
x(:,j) = s(i,j)*randn(n(i),1)+m(i,j);
end
X(t:t+n(i)-1,:) = x;
t = t+n(i);
end
|
github
|
domingomery/Balu-master
|
Bds_stratify.m
|
.m
|
Balu-master/DataSelectionAndGeneration/Bds_stratify.m
| 1,153 |
utf_8
|
13a9e28e3d401b191bafc0d99cea105a
|
% [X1,d1,X2,d2] = Bds_stratify(X,d,s)
%
% Toolbox: Balu
%
% Data Stratification (without replacement)
%
% input: (X,d) means features and ideal classification
% Bds_stratify takes randomily a portion s (s between 0 and 1) of each class
% from (X,d) to build (X1,d1). The samples not used in (X1,d1) are
% stored in (X2,d2).
%
% D.Mery, PUC-DCC, 2010
% http://dmery.ing.puc.cl
function [X1,d1,X2,d2,i1,i2] = Bds_stratify(X,d,s)
[i1,i2] = Bds_ixstratify(d,s);
X1 = X(i1,:); d1 = d(i1);
X2 = X(i2,:); d2 = d(i2);
% dmin = int8(min(d));
% dmax = int8(max(d));
%
%
% X1 = [];
% d1 = [];
% X2 = [];
% d2 = [];
% i1 = [];
% i2 = [];
%
% for k=dmin:dmax
% ik = find(d==k);
% Xk = X(ik,:);
% dk = d(ik);
% nk = length(dk);
% rk = rand(nk,1);
% [i,j] = sort(rk);
% sk = ceil(s*nk);
% if (sk>0)
% X1 = [X1; Xk(j(1:sk),:)];
% d1 = [d1; dk(j(1:sk))];
% i1 = [ii; ik(j(1:sk))];
% end
% if (sk<nk)
% X2 = [X2; Xk(j(sk+1:nk),:)];
% d2 = [d2; dk(j(sk+1:nk))];
% i2 = [i2; ik(j(sk+1:nk))];
% end
% end
|
github
|
domingomery/Balu-master
|
Bds_Adasyn.m
|
.m
|
Balu-master/DataSelectionAndGeneration/Bds_Adasyn.m
| 3,853 |
utf_8
|
de570389b3084e03d40846ad0a8c19a3
|
% [New_X, New_d] = Bds_Adasyn(X, d, smote_rate, k)
%
% Toolbox: Balu
%
% OVER-SAMPLING method, where the label for the majority class is 0
% and the label for the minority class is 1.
%
% This function implements ADASYN (Adaptive Synthetic Sampling Approach)
% for Imbalanced Learning. Its main idea is to generate minority class
% examples adaptively according to their distributions, where more
% synthetic data is created for "difficult" ones than "easy" ones.
%
% Input:
% X is a matrix with features (columns).
% d is the ideal classification for X {0, 1} where 1 is the
% minority class.
% smote_rate is the rate of the synthetic samples to be created for
% the minority class. A value of 1.0 means that 100% of the data in
% the minority class will be generated
% k is the number of neighbours to use
%
% Output:
% New_X is the new feature matrix augmented with the synthetic samples
% New_d is the new ideal classification for New_X.
%
% For more details on the theoretical description of the algorithm
% please refer to the following paper:
% HE, H. et al (2008). ADASYN: Adaptive synthetic sampling approach for
% imbalanced learning in IEEE International Joint Conference on NN, 2008
%
% This implementation use the nearestneighbour provided by Richard Brown
% and available on:
% http://www.mathworks.com/matlabcentral/fileexchange/38830-smote-synthe
% tic-minority-over-sampling-technique
% C. Mera, UNAL, 2013
function [new_X, new_d] = Bds_Adasyn(X, d, smote_rate, k)
if (nargin < 3)
smote_rate = 1.0;
k = 5;
elseif (nargin < 4)
k = 5;
end
if (smote_rate > 0)
% Points of the majority class (labeled 0)
NEG_DAT = X(d == 0,:);
NEG_DAT = NEG_DAT';
% Points of the minority class (labeled 1)
POS_DAT = X(d == 1,:);
POS_DAT = POS_DAT';
neg_size = size(NEG_DAT, 2);
pos_size = size(POS_DAT, 2);
if (pos_size < neg_size)
% Calculate the number N of synthetic data examples that need
% to be generated for the minority class
N = round(pos_size * smote_rate);
% Finding the k nearest neighbours of all the positive samples
I = nearestneighbour(POS_DAT, X', 'NumberOfNeighbours', k+1);
I = I';
% Calculate the ratio r_i
R = sum(d(I(:,2:end))==0, 2);
R = R/k;
% Normalize r_i
R = R/sum(R);
% Calculate the number of synthetic data examples that need to be
% generated for each minority example
G = round(R*N);
% Coorrect N by the effect of the round function
N = sum(G(:,1));
XX = zeros(size(POS_DAT,1), N);
aux = 0;
for i=1:pos_size
if (G(i) >= 1)
I2 = nearestneighbour(POS_DAT(:,i), POS_DAT, 'NumberOfNeighbours', k+1);
for j=1:G(i)
index = I2(1,randi(k)+1);
aux = aux + 1;
alpha = rand;
new_P = (1-alpha).*POS_DAT(:,i) + alpha.*(POS_DAT(:,index));
XX(:,aux) = new_P;
end
end
end
%Delete No-Generated samples
if (aux < N)
XX(:,aux+1:end)=[];
N = aux;
end
new_X = [X; XX'];
new_d = [d; ones(N,1)];
else
new_X = X;
new_d = d;
end
else
new_X = X;
new_d = d;
end
end
|
github
|
domingomery/Balu-master
|
Bds_CNNRule.m
|
.m
|
Balu-master/DataSelectionAndGeneration/Bds_CNNRule.m
| 1,848 |
utf_8
|
d42d82252bd1f1e3782d2aeb2dda5edb
|
% [New_X, New_d] = Bds_CNNRule(X, d)
%
% Toolbox: Balu
%
% UNDER-SAMPLING method, where the label for the majority class is 0
% and the label for the minority class is 1.
%
% This function implements the Condensed Nearest Neighbor Rule (CNN) to
% undersampling the majority class (labeled 0). CNN Rule aims to ?nd
% examples far from decision boundaries. The idea is to ?nd a consistent
% data subset Z ? X, where all the examples in X can be classi?ed
% correctly by using 1-NN in Z.
%
% Input:
% X is a matrix with features (columns).
% d is the ideal classification for X.
%
% Output:
% New_X is the new feature matrix with less elements that X.
% New_d is the new ideal classification for New_X.
%
% For more details on the theoretical description of the original
% algorithm please refer to the following paper:
% P. E. Hart (1968). The Condensed Nearest Neighbor Rule.
% IEEE Transactions on Information Theory IT-14 (1968), 515-516
%
% C. Mera, UNAL, 2013
function [new_X, new_d] = Bds_CNNRule(X, d)
% Points of the majority class (labeled 0)
NEG_DAT = X(d == 0,:);
neg_size = size(NEG_DAT, 1);
% Points of the minority class (labeled 1)
POS_DAT = X(d == 1,:);
pos_size = size(POS_DAT, 1);
% Select one data sample at random from the majority class
x = randi(neg_size);
% Create Z as all positive samples and one randomly selected negative example
Z = [POS_DAT;NEG_DAT(x,:)];
dz = ones(pos_size+1,1);
dz(end) = 0;
% Classify X with the 1-NN rule using the examples in Z
op.k = 1;
op = Bcl_knn(Z,dz,op);
ds = Bcl_knn(X,op);
INDX = d~=ds;
Z = [Z; X(INDX,:)];
new_X = Z;
new_d = [dz; d(INDX)];
end
|
github
|
domingomery/Balu-master
|
Bds_BorderSMOTE.m
|
.m
|
Balu-master/DataSelectionAndGeneration/Bds_BorderSMOTE.m
| 3,549 |
utf_8
|
408e7ed9368e3c291ab9fed6c7473698
|
% [New_X, New_d] = Bds_BorderSMOTE(X, d, smote_rate, k)
%
% Toolbox: Balu
%
% OVER-SAMPLING method, where the label for the majority class is 0
% and the label for the minority class is 1.
%
% This function implements Borderline-SMOTE an oversampling method for
% imbalanced data sets with two classes. Borderline-SMOTE is a
% modification of SMOTE. It Only use borderline examples to generate new
% data by applying SMOTE.
%
% Input:
% X is a matrix with features (columns).
% d is the ideal classification for X.
% smote_rate is the rate of the synthetic samples to be created for
% the minority class. A value of 1.0 means that 100% of the data in
% the minority class will be generated
% k is the number of neighbours to use
%
% Output:
% New_X is the new feature matrix augmented with the synthetic samples
% New_d is the new ideal classification for New_X.
%
% For more details on the theoretical description of the algorithm
% please refer to the following paper:
% Han, H. et al (2005). Borderline-SMOTE: A New Over-Sampling Method
% in Imbalanced Data Sets Learning. Advances in Intelligent Computing,
% Vol. 3644, pp 878-887, Springer.
%
% This implementation use the nearestneighbour provided by Richard Brown
% and available on:
% http://www.mathworks.com/matlabcentral/fileexchange/38830-smote-synthe
% tic-minority-over-sampling-technique
%
%
% C. Mera, UNAL, 2013
function [New_X, New_d] = Bds_BorderSMOTE(X, d, smote_rate, k)
if (nargin < 3)
smote_rate = 1.0;
k = 5;
elseif (nargin < 4)
k = 5;
end
if (smote_rate > 0)
% POS_DAT = candidate points of the minority class (labeled 1)
POS_DAT = X(d == 1,:);
POS_DAT = POS_DAT';
pos_size = size(POS_DAT, 2);
% Calculate the number N of synthetic data examples that need
% to be generated for the minority class
N = round(pos_size * smote_rate);
% If the rate es less than 1, only a random sample of the minority
% class is used
if (smote_rate < 1)
RND_IDX = randsample(pos_size, N);
POS_DAT = POS_DAT(:,RND_IDX);
smote_rate = 1;
end
% Finding the k nearest neighbours the positive points
I = nearestneighbour(POS_DAT, X', 'NumberOfNeighbours', k+1);
I = I';
[r, c] = size(I);
Xn = ones(N,1);
XX = zeros(size(POS_DAT,1), N);
j = 1;
% If the rate is a multiple of 100
while (N > 0)
for i=1:r
Z = I(i,2:k+1);
m = sum(d(Z,:)==0);
if (m < k && m >= (k/2))
I2 = nearestneighbour(POS_DAT(:,i), POS_DAT, 'NumberOfNeighbours', k+1);
for w=1:floor(smote_rate)
index = I2(1,randi(k)+1);
alpha = rand;
new_P = (1-alpha).*POS_DAT(:,i) + alpha.*(POS_DAT(:,index));
XX(:,j) = new_P;
N = N-1;
j = j+1;
if (N <= 0); break; end
end
end
if (N <= 0); break; end
end
end
New_X = [X; XX'];
New_d = [d; Xn];
else
New_X = X;
New_d = d;
end
end
|
github
|
domingomery/Balu-master
|
Bct_neighbor.m
|
.m
|
Balu-master/Clustering/Bct_neighbor.m
| 1,101 |
utf_8
|
db714d4f192e31b5f83d55db1f721304
|
% function [ds,Xc] = Bct_neighbor(X,th)
%
% Toolbox: Balu
%
% Neigbor clustering: iterative method, a sample will be added to a
% cluster if its distance to the mass center of the cluster is less than
% th, else it will be create a new cluster.
%
% X matrix of samples
% th minimal distance
% ds assigned class number
% Xc mass center of each cluster
%
% Example:
% [X,d] = Bds_gaussgen([10 1;1 10],1*ones(2,2),100*ones(2,1));
% figure(1)
% Bio_plotfeatures(X,d);
% ds = Bct_neighbor(X,4);
% figure(2)
% Bio_plotfeatures(X,ds);
%
% (c) D.Mery, PUC-DCC, 2011
% http://dmery.ing.puc.cl
function [ds,Xc] = Bct_neighbor(X,th)
m = size(X,2);
N = size(X,1);
ds = zeros(N,1);
c = 1;
ds(1) = c;
while(sum(ds>0)<N)
i0 = find(ds==0);
X0 = X(i0,:);
n0 = length(i0);
Xc = ones(n0,1)*mean(X(ds==c,:),1);
Xd = Xc-X0;
M2 = sqrt(sum(Xd.*Xd,2));
i2 = find(M2<th);
if ~isempty(i2)
ds(i0(i2)) = c;
else
c = c+1;
ds(i0(1))=c;
end
end
Xc = zeros(c,m);
for i=1:c
Xc(i,:) = mean(X(ds==i,:),1);
end
|
github
|
domingomery/Balu-master
|
Bct_spectralct.m
|
.m
|
Balu-master/Clustering/Bct_spectralct.m
| 1,340 |
utf_8
|
19a41f7ffb07e8394f853b07224832a2
|
% [idx eigvec eigval] = Bct_spectralct(W, k)
%
% Toolbox: Balu
% Spectral clustering
%
% idx -- cluster indexes (same as Matlab k-means).
% eigvec -- eigenvectors.
% eigval -- eigenvalues.
%
% W -- weighted adjacency matrix.
% k -- number of clusters.
%
% Example:
% load spectraldata
% d = ones(size(X,1),1);
% figure
% Bio_plotfeatures(X,d)
% G = Bct_knngraph2d(X, 50);
% beta = 1/0.5^2;
% [ni nj] = find(G == true);
% W = zeros(size(G));
% W(G == true) = exp(-beta*(sum((X(ni,:) - X(nj,:)).^2,2)));
% ds = Bct_spectralct(W, 3);
% figure
% Bio_plotfeatures(X,ds)
%
%
% See also Bcl_qda.
%
% (c) GRIMA-DCCUC, 2011: Cristobal Moenne
% http://grima.ing.puc.cl
function [idx eigvec eigval] = Bct_spectralct(W, k)
[eigval eigvec] = eigsmatrix(W, k);
space = eigvec(:,1:k);
for ni=1:size(space, 1)
space(ni,:) = space(ni,:)./norm(space(ni,:));
end
idx = kmeans(space, k, 'replicates', 5, 'emptyaction', 'singleton');
end
function [eigval eigvec] = eigsmatrix(W, k)
D = diag(sum(W));
[eigvec eigval] = eigs(D\W, k);
eigval = real(diag(eigval));
[dummy index] = sort(eigval, 'descend');
eigval = eigval(index);
eigvec = eigvec(:,index);
end
|
github
|
domingomery/Balu-master
|
Bct_kmeans.m
|
.m
|
Balu-master/Clustering/Bct_kmeans.m
| 1,908 |
utf_8
|
731948205dde97c0de06209f88d8605a
|
% function [ds,C] = Bct_kmeans(X,k,show)
%
% Toolbox: Balu
%
% k-means clustering
% X matrix of samples
% k number of clusters
% ds assigned class number
% C centroids of each cluster
% show = 1 display intermediate results
% show = 0 uses kmeans algortithm of vlfeat (if installed else algorithm
% of matlab).
%
% Example:
% [X,d] = Bds_gaussgen([10 1;1 10;15 15],4*ones(3,3),100*ones(3,1));
% figure(1)
% Bio_plotfeatures(X,d);
% ds = Bct_kmeans(X,3);
% figure(2)
% Bio_plotfeatures(X,ds);
%
% (c) D.Mery, PUC-DCC, 2011
% http://dmery.ing.puc.cl
function [ds,C] = Bct_kmeans(X,k,show)
if not(exist('show','var'))
show = 0;
end
X = double(X);
if show==0
if ~exist('vl_kmeans','file')
[ds,C] = kmeans(X,k);
else
% [ds,C] = vl_kmeans(X,k);
[C,ds] = vl_kmeans(X',k);
ds = ds'; C = C';
end
else
fprintf('Computing K-means clustering for %d clusters and %dx%d data...\n',k,size(X,1),size(X,2));
[N,P] = size(X);
d = fix(k*0.999*rand(N,1)+1);
ok = 0;
C = zeros(k,P);
while not(ok)
Dk = Inf*ones(N,k);
for i=1:k
ii = find(d==i);
if isempty(ii)
mi = rand(1,P);
else
mi = mean(X(ii,:),1);
end
D = X-ones(N,1)*mi;
D2 = D.*D;
Dk(:,i) = sum(D2,2);
C(i,:) = mi;
end
[i,j] = min(Dk,[],2);
ds = j;
e = norm(d-ds);
d = ds;
if e<1
ok = 1;
end
if show
if P<=3
clf
Bio_plotfeatures(X,ds)
else
clf
Bio_plotfeatures(X(:,1:3),ds)
end
pause(1)
end
end
end
|
github
|
domingomery/Balu-master
|
Bct_neighbor2D.m
|
.m
|
Balu-master/Clustering/Bct_neighbor2D.m
| 1,598 |
utf_8
|
38bbb4bf29df45f9bb0c50453e1835a7
|
% function [ds,Xc] = Bct_neighbor(X,th)
%
% Toolbox: Balu
%
% Neigbor clustering: iterative method, a sample will be added to a
% cluster if its distance to the mass center of the cluster is less than
% th, else it will be create a new cluster.
%
% X matrix of samples
% th minimal distance
% ds assigned class number
% Xc mass center of each cluster
%
% Example:
% [X,d] = Bds_gaussgen([10 1;1 10],1*ones(2,2),100*ones(2,1));
% figure(1)
% Bio_plotfeatures(X,d);
% ds = Bct_neighbor(X,4);
% figure(2)
% Bio_plotfeatures(X,ds);
%
% (c) D.Mery, PUC-DCC, 2011
% http://dmery.ing.puc.cl
function [ds,Xc] = Bct_neighbor2D(X,th)
m = size(X,1);
nimg = size(X,2);
N = size(X,3);
ds = zeros(N,1);
c = 1;
ds(1) = c;
while(sum(ds>0)<N)
i0 = find(ds==0);
X0 = X(:,:,i0);
n0 = length(i0);
Xc = zeros(m,nimg,n0);
for k=1:n0
Xc(:,:,k) = mean(X0(:,:,k),2)*ones(1,nimg);
end
Xd = Xc-X0;
M2 = sqrt(sum(Xd.*Xd,1));
t = mean(M2,2);
i2 = find(t<th);
if ~isempty(i2)
ds(i0(i2)) = c;
else
c = c+1;
ds(i0(1))=c;
end
end
Xc = zeros(m,nimg,c);
for i=1:c
Xi = X(:,:,ds==i);
ni = sum(ds==i);
T = zeros(nimg,ni);
T(:) = sum(Xi,1);
T = T';
for p=1:m
for q=1:nimg
s = 0;
nr = 0;
for r=1:ni
if T(r,q)>0
s = s + Xi(p,q,r);
nr = nr+1;
end
end
if nr>0
Xc(p,q,i) = s/nr;
end
end
end
end
|
github
|
domingomery/Balu-master
|
Bct_medoidshift.m
|
.m
|
Balu-master/Clustering/Bct_medoidshift.m
| 1,027 |
utf_8
|
0d29036ecc03408541afde75b95011e2
|
% function [ds,map] = Bct_medoidshift(X, sigma, k)
%
% Toolbox: Balu
%
% Medoidshift clustering
% X matrix of samples.
% sigma: standard deviation of the Gaussian Parzen window.
% map is the map of the tree.
% ds assigned class number.
% k number of clusters.
% map are the reduced coordinates.
%
% Implementation based on:
% Vedaldi,A; Stefano, S. (2008): Quick Shift and Kernel Methods for
% Mode Seeking, ECCV2008.
%
% Example:
% [X,d] = Bds_gaussgen([10 1;1 10;15 15],4*ones(3,3),100*ones(3,1));
% figure(1)
% Bio_plotfeatures(X,d);
% ds = Bct_medoidshift(X,2,3);
% figure(2)
% Bio_plotfeatures(X,ds);
%
% (c) D.Mery, PUC-DCC, 2010
% http://dmery.ing.puc.cl
function [ds,map] = Bct_medoidshift(X, sigma, k)
G = X';
[d,N] = size(G) ;
oN = ones(N,1) ;
od = ones(d,1) ;
n = (G'.*G')*od ;
D = n*oN' + oN*n' - 2*(G'*G) ;
F = - exp(- .5 * D' / sigma^2) ;
Q = n * (oN'*F) - 2 * G' * (G*F) ;
[drop,map] = max(Q) ;
map = map';
ds = Bct_kmeans(map,k);
|
github
|
domingomery/Balu-master
|
Bct_meanshift.m
|
.m
|
Balu-master/Clustering/Bct_meanshift.m
| 1,376 |
utf_8
|
157a796adf09812bddd41af3e7d191a4
|
% function [ds,Z] = Bct_meanshift(X, sigma)
%
% Toolbox: Balu
%
% Meanshift clustering
% X matrix of samples
% sigma: standard deviation of the Gaussian Parzen window
% ds assigned class number.
% Z are the reduced coordinates.
%
% Implementation based on:
% Vedaldi,A; Stefano, S. (2008): Quick Shift and Kernel Methods for
% Mode Seeking, ECCV2008.
%
% Example:
% [X,d] = Bds_gaussgen([10 1;1 10;15 15],4*ones(3,3),100*ones(3,1));
% figure(1)
% Bio_plotfeatures(X,d);
% ds = Bct_meanshift(X,2);
% figure(2)
% Bio_plotfeatures(X,ds);
%
% (c) D.Mery, PUC-DCC, 2010
% http://dmery.ing.puc.cl
function [ds,Z] = Bct_meanshift(X, sigma)
G = X';
[d,N] = size(G) ;
oN = ones(N,1) ;
od = ones(d,1) ;
n = (G'.*G')*od ;
Z = G ;
T = 100 ;
for t=1:T
m = (Z'.*Z')*od ;
D = m*oN' + oN*n' - 2*(Z'*G) ;
F = - exp(- .5 * D' / sigma^2) ;
Y = F ./ (oN * (oN'*F)) ;
Z = G*Y ;
end
Z = Z';
ds = zeros(N,1);
ds(1)=1;
ms = Z(1,:);
ns = 1;
r = 1;
s = sigma*2;
for i=2:N
mi = Z(i,:);
D = ms-ones(r,1)*mi;
D2 = D.*D;
Dk = sum(D2,2);
[ii,jj] = min(Dk');
if ii<s
ds(i) = jj(1);
ms(jj,:) = ms(jj,:)*ns(jj)+mi;
ns(jj)=ns(jj)+1;
ms(jj,:) = ms(jj,:)/ns(jj);
else
r = r+1;
ms = [ms;mi];
ns = [ns;1];
ds(i)=r;
end
end
|
github
|
domingomery/Balu-master
|
Bio_printfeatures.m
|
.m
|
Balu-master/InputOutput/Bio_printfeatures.m
| 1,758 |
utf_8
|
fa30eae8aa7a4319e561efd2b7e19a4b
|
% Bprintfeatures(X,Xn) % for features with feature names
% Bprintfeatures(X) % for feature values only
%
% Toolbox: Balu
% Display extracted features.
% Xn: feature names (matrix mxp, one row per each string of p
% characters)
% X: feature values (vector 1xm for m features)
% Xu: feature units (matrix mxq, one row per each string of q
% characters)
%
% These variables are the outputs of Bgeofeatures or Bintfeatures.
%
% The output of Bprintfeatures is like this:
%
% 1 center of grav i [pixels] 163.297106
% 2 center of grav j [pixels] 179.841850
% 3 Height [pixels] 194.000000
% 4 Width [pixels] 196.000000
% 5 Area [pixels] 29361.375000
% : : : :
%
% Example 1: Display of standard geometric features of testimg1.jpg
% I = imread('testimg1.jpg'); % input image
% R = Bsegbalu(I); % segmentation
% [X,Xn,Xu] = Bfg_standard(R); % standard geometric features
% Bprintfeatures(X,Xn,Xu)
%
% Example 2: Display of first 5 samples of datagauss.mat
% load datagauss
% Xn = ['[length]';'[weigh] '];
% Xu = ['cm';'kg'];
% for i=1:5
% fprintf('Sample %d:\n',i);
% Bprintfeatures(X(i,:),Xn,Xu)
% Benterpause
% end
%
%
% See also Bplotfeatures.
%
% (c) D.Mery, PUC-DCC, 2010
% http://dmery.ing.puc.cl
function Bprintfeatures(X,Xn)
N = length(X);
if ~exist('Xn','var')
Xn = char(zeros(N,16));
end
for k=1:size(Xn,1)
fprintf('%3d %s %f\n',k,Xn(k,:),X(k));
end
|
github
|
domingomery/Balu-master
|
Bio_labelimage.m
|
.m
|
Balu-master/InputOutput/Bio_labelimage.m
| 312 |
utf_8
|
6f25dff925685ad79454ad4d48cbb1e1
|
% (c) D.Mery, PUC-DCC, 2011
% http://dmery.ing.puc.cl
function d = Bio_labelimage(f)
d = zeros(f.imgmax-f.imgmin+1,1);
for i=f.imgmin:f.imgmax
[I,st] = Bio_loadimg(f,i);
imshow(I(:,:,1),[])
fprintf('\n--- processing image %s...\n',st);
d(i-f.imgmin+1,1) = input('Label for this image? ');
end
|
github
|
domingomery/Balu-master
|
Bio_copyfiles.m
|
.m
|
Balu-master/InputOutput/Bio_copyfiles.m
| 674 |
utf_8
|
144400f6ca2023cf5376ddcd39c35c0b
|
% Bio_copyfiles(prefix1,prefix2)
%
% Toolbox: Balu
% Copy files prefix1* to prefix2*.
%
% This program convert all files starting with prefix1 to new files with
% prefix2.
%
% Example:
% Bio_copyfiles('images','img') % converts all files 'images' to 'img'
%
% (c) GRIMA-DCCUC, 2011
% http://grima.ing.puc.cl
function Bio_copyfiles(prefix1,prefix2)
d1 = dir([prefix1 '*']);
t1 = length(prefix1);
n = length(d1);
if n>0
fprintf('copying %d files...\n',n)
if ispc
fcp = '!copy ';
else
fcp = '!cp ';
end
for i=1:n
f1 = d1(i).name;
f2 = [prefix2 f1(t1+1:end)];
eval([fcp f1 ' ' f2]);
end
end
|
github
|
domingomery/Balu-master
|
Bio_statusbar.m
|
.m
|
Balu-master/InputOutput/Bio_statusbar.m
| 7,905 |
utf_8
|
dab9d1909a18344b0a96efd07da39d40
|
%Display a status/progress bar and inform about the elapsed
%as well as the remaining time (linear estimation).
%
%Synopsis:
%
% f = Bio_statusbar
% Get all status/progress bar handles.
%
% f = Bio_statusbar(title)
% Create a new status/progress bar. If title is an empty
% string, the default 'Progress ...' will be used.
%
% f = Bio_statusbar(title,f)
% Reset an existing status/progress bar or create a new
% if the handle became invalid.
%
% f = Bio_statusbar(done,f)
% For 0 < done < 1, update the progress bar and the elap-
% sed time. Estimate the remaining time until completion.
% On user abort, return an empty handle.
%
% v = Bio_statusbar('on')
% v = Bio_statusbar('off')
% Set default visibility for new statusbars and return
% the previous setting.
%
% v = Bio_statusbar('on',f)
% v = Bio_statusbar('off',f)
% Show or hide an existing statusbar and return the last
% visibility setting.
%
% delete(Bio_statusbar)
% Remove all status/progress bars.
%
% drawnow
% Refresh all GUI windows.
%
% Example:
% f=Bio_statusbar('Wait some seconds ...');
% for p=0:0.01:1
% pause(0.2);
% if isempty(Bio_statusbar(p,f))
% break;
% end
% end
% if ishandle(f)
% delete(f);
% end
%
% Copyright (c) 2004, Marcel Leutenegger
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
% * Neither the name of the Ecole Polytechnique F??d??rale de Lausanne,
% Laboratoire d'Optique Biom??dicale nor the names
% of its contributors may be used to endorse or promote products derived
% from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
function f=Bio_statusbar(p,f)
persistent visible;
%vr2014b = strcmp(version('-release'),'2014b');
vr_new = versionyear()>=2014;
if nargin < nargout % get handles
o='ShowHiddenHandles';
t=get(0,o);
set(0,o,'on');
f=findobj(get(0,'Children'),'flat','Tag','StatusBar');
set(0,o,t);
return;
end
curtime=86400*now;
if vr_new
tt = nargin == 2 && isa(check(f),'matlab.ui.Figure');
else
tt = nargin == 2 && check(f);
end
if nargin & ischar(p)
if isequal(p,'on') | isequal(p,'off')
if nargin == 2
if check(f) % show/hide
v=get(f,'Visible');
set(f,'Visible',p);
end
else
v=visible;
visible=p; % default
if ~strcmp(v,'off')
v='on';
end
end
if nargout
f=v;
end
else
if nargin == 2 & check(f) % reset
modify(f,'Line','XData',[4 4 4]);
modify(f,'Rect','Position',[4 54 0.1 22]);
modify(f,'Done','String','0');
modify(f,'Time','String','0:00:00');
modify(f,'Task','String','0:00:00');
else
f=create(visible); % create
end
if p
set(f,'Name',p);
end
set(f,'CloseRequestFcn','set(gcbo,''UserData'',-abs(get(gcbo,''UserData'')));','UserData',[curtime curtime 0]);
end
drawnow;
elseif tt % update
t=get(f,'UserData');
if any(t < 0) % confirm
if p >= 1 | isequal(questdlg({'Are you sure to stop the execution now?',''},'Abort requested','Stop','Resume','Resume'),'Stop')
delete(f);
f=[]; % interrupt
return;
end
t=abs(t);
set(f,'UserData',t); % continue
end
p=min(1,max([0 p]));
%
% Refresh display if
%
% 1. still computing
% 2. computation just finished
% or
% more than a second passed since last refresh
% or
% more than 0.4% computed since last refresh
%
if any(t) & (p >= 1 | curtime-t(2) > 1 | p-t(3) > 0.004)
set(f,'UserData',[t(1) curtime p]);
t=round(curtime-t(1));
h=floor(t/60);
modify(f,'Line','XData',[4 4+248*p 4+248*p]);
modify(f,'Rect','Position',[4 54 max(0.1,248*p) 22]);
modify(f,'Done','String',sprintf('%u',floor(p*100+0.5)));
modify(f,'Time','String',sprintf('%u:%02u:%02u',[floor(h/60);mod(h,60);mod(t,60)]));
if p > 0.05 | t > 60
t=ceil(t/p-t);
if t < 1e7
h=floor(t/60);
modify(f,'Task','String',sprintf('%u:%02u:%02u',[floor(h/60);mod(h,60);mod(t,60)]));
end
end
if p == 1
set(f,'CloseRequestFcn','delete(gcbo);','UserData',[]);
end
drawnow;
end
end
if ~nargout
clear;
end
%Check if a given handle is a progress bar.
%
function f=check(f)
%vr2014b = strcmp(version('-release'),'2014b');
if versionyear>=2014
if isa(f,'matlab.ui.Figure') && ishandle(f(1)) && isequal(get(f(1),'Tag'),'StatusBar')
f=f(1);
else
f=[];
end
else
if f && ishandle(f(1)) && isequal(get(f(1),'Tag'),'StatusBar')
f=f(1);
else
f=[];
end
end
%Create the progress bar.
%
function f=create(visible)
if ~nargin | isempty(visible)
visible='on';
end
s=[256 80];
t=get(0,'ScreenSize');
f=figure('DoubleBuffer','on','HandleVisibility','off','MenuBar','none','Name','Progress ...','IntegerHandle','off','NumberTitle','off','Resize','off','Position',[floor((t(3:4)-s)/2) s],'Tag','StatusBar','ToolBar','none','Visible',visible);
a.Parent=axes('Parent',f,'Position',[0 0 1 1],'Visible','off','XLim',[0 256],'YLim',[0 80]);
%
%Horizontal bar
%
rectangle('Position',[4 54 248 22],'EdgeColor','white','FaceColor',[0.6 0.6 0.6],a);
line([4 4 252],[55 76 76],'Color',[0.5 0.5 0.5],a);
rectangle('Position',[4 54 0.1 22],'EdgeColor','white','FaceColor',[0.1 0.3 1],'Tag','Rect',a);
line([4 4 4],[54 54 77],'Color',[0.2 0.2 0.2],'Tag','Line',a);
%
%Description texts
%
a.FontWeight='bold';
a.Units='pixels';
a.VerticalAlignment='middle';
text(136,66,1,'%',a);
text(16,36,'Elapsed time:',a);
text(16,20,'Remaining:',a);
text(190,36,'hh:mm:ss',a);
text(190,20,'hh:mm:ss',a);
%
%Information texts
%
a.HorizontalAlignment='right';
text(136,66,1,'0',a,'Tag','Done');
text(178,36,'0:00:00',a,'Tag','Time');
text(178,20,'0:00:00',a,'Tag','Task');
%Modify an object property.
%
function modify(f,t,p,v)
set(findobj(f,'Tag',t),p,v);
function y = versionyear()
st = version('-release');
y = str2num(st(1:4)); %#ok<ST2NM>
|
github
|
domingomery/Balu-master
|
Bio_showconfusion.m
|
.m
|
Balu-master/InputOutput/Bio_showconfusion.m
| 867 |
utf_8
|
dd4bbd143405a76194a42ac2a3a6e07c
|
%function Bio_showconfusion(C)
%
% Toolbox: Balu
% Show confusion matrix C in a color 2D representation.
%
%
% Example:
%
% % Simulation of a 10x10 confussion matrix
% C = rand(10,10)+2*eye(10);C = C/max(C(:));
%
% Bio_showconfusion(C)
% (c) GRIMA-DCCUC, 2013
% http://grima.ing.puc.cl
%
function Bio_showconfusion(C)
minC = min(C(:));
maxC = max(C(:));
[N,M] = size(C);
if minC<0
error('There are negative values.');
end
if maxC>100
error('Maximal value of C should be 100.')
end
if N~=M
error('Matrix should be square.')
end
if maxC<=1
C = 100*C;
end
jet100 = imresize(jet,[100 3],'nearest');
clf;
T = 256;
imshow(imresize(round(C),[T T],'nearest'),jet100)
axis off
hold on
sq = 256/N;
for i=1:N
y = T*i/N-sq/2;
for j=1:N
x = T*j/N-0.75*sq;
text(x,y,num2str(round(C(i,j))))
end
end
colorbar
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.