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
domingomery/Balu-master
Bio_manyplot.m
.m
Balu-master/InputOutput/Bio_manyplot.m
1,215
utf_8
f88fda7a9bd7b5d2f13dd5d3ad52e3d2
% Bio_manyplot(x,y,labels,xlab,showper) % % Toolbox: Balu % % Plot of many (x,y) graphs % % Input: % - x could be a column vector with n elements or a matrix with % nxm elements % - y is a matrix with nxm elements % Output: % - a plot of m curves, each curve has n points with different colors % % % Example 1: same x for different y % clf % x = (0:0.01:1)'; % y = [sin(x*2*pi) cos(x*pi) sin(x*pi)]; % Bio_manyplot(x,y) % grid on % legend({'curve-1','curve-2','curve-3'}) % % Example 2: different x for different y % clf % x = [sort(rand(100,1)) sort(rand(100,1)) sort(rand(100,1))]; % y = [sin(x(:,1)*2*pi) cos(x(:,2)*pi) sin(x(:,3)*pi)]; % Bio_manyplot(x,y) % grid on % legend({'curve-1','curve-2','curve-3'}) % % (c) Domingo Mery, 2019 % http://dmery.ing.puc.cl function Bio_manyplot(x,y) hold on set(gca,'FontSize',12) sc = 'bgrcmykbgrcmykbkbgrcmy'; sq = 'sdvo^>sdvo^>vo^>sd'; sl = '-:-:-:-:-:-:-:-:-:-:-:-:-:'; p = size(y,2); m = size(x,2); if m==1 x = repmat(x,[1 p]); end for i=1:p plot(x(:,i),y(:,i),[sq(i) sl(i)],'LineWidth',2,... 'MarkerEdgeColor',sc(i),... 'MarkerFaceColor',sc(i+1),... 'MarkerSize',5) end
github
domingomery/Balu-master
Bio_plotfeatures.m
.m
Balu-master/InputOutput/Bio_plotfeatures.m
4,944
utf_8
ef2f13c1a1d21d79d578bfa400278972
% Bio_plotfeatures(X,d,Xn) % % Toolbox: Balu % Plot features X acording classification d. If the feature names are % given in Xn then they will labeled in each axis. % % For only one feature, histograms are ploted. % For two (or three) features, plots in 2D (or 3D) are given. % For m>3 features, m x m 2D plots are given (feature i vs. feature j) % % Example 1: 1D & 2D % load datagauss % simulated data (2 classes, 2 features) % figure(1) % Bio_plotfeatures(X(:,1),d,'x1') % histogram of feature 1 % figure(2) % Bio_plotfeatures(X,d) % plot feature space in 2D (2 features) % % Example 2: 3D % load datareal % real data % X = f(:,[221 175 235]); % only three features are choosen % Bio_plotfeatures(X,d) % plot feature space in 3D (3 features) % % Example 3: 5D (using feature selection) % load datareal % real data % op.m = 5; % 5 features will be selected % op.s = 0.75; % only 75% of sample will be used % op.show = 0; % display results % op.b.name = 'fisher'; % definition SFS with Fisher % s = Bfs_balu(f,d,op); % feature selection % Bio_plotfeatures(f(:,s),d) % plot feature space for 5 features % % See also Bev_roc. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % function Bio_plotfeatures(X,d,Xn) if ~exist('Xn','var') Xn = []; end m = size(X,2); if m>9 error('Bio_plotfeatures for %d features makes %d plots.',m,m*m) end scflag = 0; if size(d,2)==2 sc = d(:,2); d = d(:,1); scflag = 1; end dmin = min(d); dmax = max(d); col = 'gbrcmykbgrcmykbgrcmykbgrcmykgbrcmykbgrcmykbgrcmykbgrcmykgbrcmykbgrcmykbgrcmykbgrcmyk'; mar = 'ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^ox+v^'; % clf warning off r = sprintf('%s',39); warning on s = 'legend('; for k = dmin:dmax s = [s r sprintf('class %d',k) r ]; % s = [s r sprintf('class %d',k-1) r ]; if k<dmax s = [s ',']; else s = [s ');']; end end if (m<4) switch m case 1 for k = dmin:dmax [h,x] = hist(X(d==k),100); dx = x(2)-x(1); A = sum(h)*dx; x = [x(1)-dx x x(end)+dx]; h = [0 h 0]; plot(x,h/A,col(k+1)); hold on end if ~isempty(Xn) xlabel(Xn); else xlabel('feature value'); end ylabel('PDF'); case 2 if isempty(Xn) Xn = ['feature value 1';'feature value 2']; end for k = dmin:dmax ii = find(d==k); plot(X(ii,1),X(ii,2),[col(k+1) mar(k+1)]); hold on if scflag for ic=1:length(ii) text(X(ii(ic),1),X(ii(ic),2),[' ' num2str(sc(ii(ic)))]); end end end title('feature space'); xlabel(Xn(1,:)); ylabel(Xn(2,:)); case 3 for k = dmin:dmax ii = find(d==k); plot3(X(ii,1),X(ii,2),X(ii,3),[col(k+1) mar(k+1)]); hold on if scflag for ic=1:length(ii) text(X(ii(ic),1),X(ii(ic),2),X(ii(ic),3),[' ' num2str(sc(ii(ic)))]); end end end if ~isempty(Xn) xlabel(Xn(1,:)); ylabel(Xn(2,:)); zlabel(Xn(3,:)); else xlabel('feature value 1'); ylabel('feature value 2'); zlabel('feature value 3'); end end eval(s) else l = 1; for j=1:m for i=1:m zi = X(:,i); zj = X(:,j); subplot(m,m,l); l = l+1; for k = dmin:dmax ii = find(d==k); plot(zi(ii),zj(ii),[col(k+1) mar(k+1)]); hold on if scflag for ic=1:length(ii) text(zi(ii(ic)),zj(ii(ic)),[' ' num2str(sc(ii(ic)))]); end end end if ~isempty(Xn) xl = Xn(i,:); yl = Xn(j,:); else xl = sprintf('z_%d',i); yl = sprintf('z_%d',j); end if i==1 ylabel(yl) end if j==m xlabel(xl) end end end end
github
domingomery/Balu-master
Bio_sendmail.m
.m
Balu-master/InputOutput/Bio_sendmail.m
1,611
utf_8
55f1122029d857abda5f30fe1ef3f6de
% Bio_sendmail(mymail,mypassword,mailto,subject) % Bio_sendmail(mymail,mypassword,mailto,subject,message) % Bio_sendmail(mymail,mypassword,mailto,subject,message,attachment) % % Toolbox: Balu % Send e-mail % % Send an e-mail form mymail to mailto, with subject, message (optionsl) % and attachment (optional). Ir requires the password of mymail. % % Example 1: % % x=10;y=20; % msg1 = sprintf('x=%d',x) % msg2 = sprintf('y=%d',y) % Bio_sendmail('[email protected]','johnssszzz12','[email protected]','New results',{'Hi Mary,','here are the results:',msg1,msg2,'John'}); % % % Example 2: % % Bio_sendmail('[email protected]','johnssszzz12','[email protected]','Output Image','Hi Mary, I am sending you the image. John','image.jpg'); % % See also sendmail. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % function Bio_sendmail(mymail,mypassword,mailto,subject,message,attachment) fprintf('Sending e-mail to %s...\n',mailto); setpref('Internet','E_mail',mymail); setpref('Internet','SMTP_Server','smtp.gmail.com'); setpref('Internet','SMTP_Username',mymail); setpref('Internet','SMTP_Password',mypassword); props = java.lang.System.getProperties; props.setProperty('mail.smtp.auth','true'); props.setProperty('mail.smtp.socketFactory.class','javax.net.ssl.SSLSocketFactory'); props.setProperty('mail.smtp.socketFactory.port','465'); if exist('message','var') if exist('attachment','var') sendmail(mailto,subject,message,attachment); fprintf('>> attaching file %s...\n',attachment); else sendmail(mailto,subject,message); end else sendmail(mailto,subject); end
github
domingomery/Balu-master
Bio_findex.m
.m
Balu-master/InputOutput/Bio_findex.m
436
utf_8
ce9b6a520e7a8e6ea15dd58439740828
% Obtain the index number of the feature wich names contain a given string. function [ix,fnix] = Bio_findex(fn,str,inc) if ~exist('inc','var') inc = 1; end [N,M] = size(fn); n = length(str); T=ones(N,1)*str; ix = []; for i=1:M-n+1 D = sum(abs(T-fn(:,i:i+n-1))')'; ii = find(D==0); if ~isempty(ii) ix = [ix;ii]; end end if not(inc) ii = (1:N)'; ii(ix) = []; ix = ii; end fnix = fn(ix,:);
github
domingomery/Balu-master
Bio_decisionline.m
.m
Balu-master/InputOutput/Bio_decisionline.m
1,513
utf_8
05d064a41f2cf114260a6d383b1815c9
% Bio_decisionline(X,d,op) % % Toolbox: Balu % % Diaplay a 2D feature space and decision line. % % X: Sample data % d: classification of samples % op: output of a trained classifier. % % Example: % load datagauss % simulated data (2 classes, 2 features) % Xn = ['\beta_1';'\beta_2']; % b(1).name = 'knn'; b(1).options.k = 5; % KNN with 5 neighbors % b(2).name = 'lda'; b(2).options.p = []; % LDA % b(3).name = 'svm'; b(3).options.kernel = 4; % rbf-SVM % op = b; % op = Bcl_structure(X,d,op); % close all % Bio_decisionline(X,d,Xn,op); % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function Bio_decisionline(X,d,Xn,op) if size(X,2)~=2 error('Bio_decisionline works for two features only.') end clf Bio_plotfeatures(X,d,Xn); n = length(op); hold on ax = axis; s=0.1; x = (ax(1)):s:(ax(2)); nx = length(x); y = (ax(3)):s:(ax(4)); ny = length(y); rx = ones(ny,1)*x; ry = y'*ones(1,nx); XXt = [rx(:) ry(:)]; op = Bcl_structure(X,d,op); dt = Bcl_structure(XXt,op); dmin = min(d); dmax = max(d); scol = 'ycwkbr'; tcol = 'brgywk'; close all for k=1:n figure Bio_plotfeatures(X,d,Xn); title(op(k).options.string) for i=dmin:dmax ii = find(dt(:,k)==i); plot(XXt(ii,1),XXt(ii,2),[scol(i-dmin+1) 'o']); ii = find(d==i); plot(X(ii,1),X(ii,2),[tcol(i-dmin+1) 'x']); end end
github
domingomery/Balu-master
Bio_fmtconv.m
.m
Balu-master/InputOutput/Bio_fmtconv.m
592
utf_8
56ba969fa5f60391596fb27318ff012b
% Bio_fmtconv(fmt1,fmt2) % % Toolbox: Balu % Image format conversion from format fmt1 to fmt2. % % This program convert all fmt1 images of current directory to fmt2 % images. fmt1 and fmt2 are strings. % % Example: % Bio_fmtconv('jpg','png') % converts all jpg images into png images % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl function Bio_fmtconv(fmt1,fmt2) f1 = dir(['*.' fmt1]); t1 = length(fmt1); n = length(f1); if n>0 for i=1:n fi1 = f1(i).name; I = imread(fi1); fi2 = [fi1(1:end-t1) fmt2]; imwrite(I,fi2,fmt2); end end
github
domingomery/Balu-master
Bio_edgeview.m
.m
Balu-master/InputOutput/Bio_edgeview.m
1,561
utf_8
97894a03219d2b5a9ad0fb6ad1fc785a
% Bio_edgeview(B,E,c,g) % % Toolbox: Balu % Display gray or color image I overimposed by color pixels determined % by binary image E. Useful to display the edges of an image. % Variable c is the color vector [r g b] indicating the color to be displayed % (default: c = [1 0 0], i.e., red) % Variable g is the number of pixels of the edge lines, default g = 1 % % Example to display a red edge of a food: % I = imread('testimg1.jpg'); % Input image % [R,E] = Bim_segbalu(I); % Segmentation % Bio_edgeview(I,bwperim(E),[0 1 0],3) % perimeter with 3 pixels will be % % displayed ingreen ([0 1 0] for [R G B]) % % D.Mery, PUC-DCC, Apr. 2008-2019 % http://dmery.ing.puc.cl % function Bio_edgeview(B,E,cc,g) if not(exist('cc','var')) cc = [1 0 0]; end if not(exist('g','var')) g = 1; end B = double(B); if max(B(:))>1 B = B/256; end if (size(B,3)==1) [N,M] = size(B); J = zeros(N,M,3); J(:,:,1) = B; J(:,:,2) = B; J(:,:,3) = B; B = J; end B1 = B(:,:,1); B2 = B(:,:,2); B3 = B(:,:,3); Z = B1==0; Z = and(Z,B2==0); Z = and(Z,B3==0); ii = find(Z==1); if not(isempty(ii)) B1(ii) = 1/256; B2(ii) = 1/256; B3(ii) = 1/256; end warning off E = imdilate(E,ones(g,g)); ii = find(E==1); B1(ii) = cc(1)*255; B2(ii) = cc(2)*255; B3(ii) = cc(3)*255; Y = double(B); Y(:,:,1) = B1; Y(:,:,2) = B2; Y(:,:,3) = B3; imshow(uint8(Y*256)) drawnow warning on
github
domingomery/Balu-master
Bio_plotroc.m
.m
Balu-master/InputOutput/Bio_plotroc.m
910
utf_8
416a3f90f5d3101cdce92f66261d786e
% Bio_plotroc(FPR,TPR,col) % % Toolbox: Balu % Plot ROC curve and fit to an exponetial curve % % Example: % % th = 3;x = 0:0.05:1; y = 1-exp(-3*x)+randn(1,21)*0.05; % Bio_plotroc(x,y) % % D.Mery, PUC-DCC, Apr. 2013 % http://dmery.ing.puc.cl % function [AUC,TPRs,FPRs,TPR05] = Bio_plotroc(x,y,col_line,col_point) if ~exist('col_line','var') col_line = 'b'; end if ~exist('col_point','var') col_point = 'r.'; end % clf plot(x,y,col_point) ths = fminsearch(@thest,1,[],x,y); xs = 0:0.005:1; a = 1/(1-exp(-ths)); ys = a*(1-exp(-ths*xs)); AUC = a*(1-exp(-ths)/ths-1/ths); hold on plot(xs,ys,col_line) d = xs.*xs + (1-ys).*(1-ys); [~,ii] = min(d); TPRs = ys(ii(1)); FPRs = xs(ii(1)); ii = find(xs==0.05); TPR05 = ys(ii(1)); plot(FPRs,TPRs,[col_point(1) '*']) xlabel('FPR') ylabel('TPR') end function err = thest(th,x,y) a = 1/(1-exp(-th)); ys = a*(1-exp(-th*x)); err = norm(y-ys); end
github
domingomery/Balu-master
Bio_segshow.m
.m
Balu-master/InputOutput/Bio_segshow.m
1,424
utf_8
f50243f7c3b4c583e1508bb678c5d855
% Bio_segshow(I,p) % % Toolbox: Balu % Display original image and segmented image % % Bimshow display 4 images: % 1: Original image (matrix I) % 2: Segmented (using command Bsegbalu) % 3: High contrast (using command Bsegbalu) % 4: Edges (using Bedgeview) % % p is the parameter used by command Bsegbalu. % % Example 1: Segmentation using Balu segmentation algorithm % I = imread('testimg1.jpg'); % Bio_segshow(I) % Repeat this examples for images testimg2, testimg3 and testimg4. Last % test image requires R = Bimshow(I,-0.1) for better results. % % Example 2: Segmentation using PCA and with more sensibility % I = imread('testimg2.jpg'); % Bio_segshow(I,'Bim_segpca',-0.15) % % Example 3: The name of the image can be given as argument % Bio_segshow('testimg4.jpg','Bim_segmaxfisher',-0.1) % % See also Bim_segbalu. % % D.Mery, PUC-DCC, May 2008 % http://dmery.ing.puc.cl % function Bio_segshow(I,segname,p) if not(exist('segname','var')) segname = 'Bim_segbalu'; end if compare(class(I),'char')==0 I = imread(I); end if not(exist('p','var')) p = 0; end fsname = ['[R,E,J] = ' segname '(I,p);']; eval(fsname); subplot(2,2,1);imshow(I);title('original image') subplot(2,2,2);imshow(R);title('segmented image') subplot(2,2,3);imshow(J);title('high contrast image') subplot(2,2,4);Bio_edgeview(I,imdilate(E,ones(3,3)));title('edge image')
github
domingomery/Balu-master
Bio_drawellipse.m
.m
Balu-master/InputOutput/Bio_drawellipse.m
1,213
utf_8
78e8e0a8b6677be967be516b6691e0ca
% Bio_drawellipse(v,ecol) % % Toolbox: Balu % Draws an ellipse with a(1)x^2 + a(2)xy + a(3)y^2 + a(4)x + a(5)y + a(6) = 0 % ecol is the color of the ellipse % % Extracted from http://homepages.inf.ed.ac.uk/rbf/CVonline/ % CVonline: The Evolving, Distributed, Non-Proprietary, On-Line Compendium % of Computer Vision % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl function Bio_drawellipse(v,ecol) % convert to standard form: ((x-cx)/r1)^2 + ((y-cy)/r2)^2 = 1 % rotated by theta % v = solveellipse(a); % draw ellipse with N points if not(exist('ecol','var')) ecol = 'b'; end n = size(v,1); hold on for r=1:n ae = v(r,3); be = v(r,4); theta = v(r,5); mcx = v(r,1); mcy = v(r,2); if n>1 text(mcx,mcy,num2str(r)) end N = 100; dx = 2*pi/N; R = [ [ cos(theta) sin(theta)]', [-sin(theta) cos(theta)]']; X = zeros(N+1); Y = X; for i = 1:N ang = i*dx; x = ae*cos(ang); y = be*sin(ang); d1 = R*[x y]'; X(i) = d1(1) + mcx; Y(i) = d1(2) + mcy; end X(N+1) = X(1); Y(N+1) = Y(1); plot(X,Y,ecol) end
github
domingomery/Balu-master
Bio_maillist.m
.m
Balu-master/InputOutput/Bio_maillist.m
1,572
utf_8
401aa7f4de4ad67c91080287caf7f9eb
% Bio_maillist(mymail,mypassword,mails,subject,heads,body,signature) % % Toolbox: Balu % Send e-mail list % % Send an e-mail form mymail to mails, with subject, message, head(s) and % signature. Ir requires the password of mymail. % % mails = {'[email protected]','[email protected]','[email protected]'}; % heads = {'Hi Peter:','Dear Rosa:','Hello Tomas:'}; % message = {'Please do not forget the next meeting on Monday.'}; % subject = {'Next meeting'}; % signature = {'Regards',' ','John',' ','----------------------------------','Prof. John Schmidt','Departmento of Computer Science','University of ...','http://www.usw.edu','----------------------------------'}; % Bio_maillist('[email protected]','johnssszzz12',mails,subject,heads,message,signature); % % See also Bio_sendmail. % % (c) GRIMA-DCCUC, 2012 % http://grima.ing.puc.cl function Bio_maillist(mymail,mypassword,mails,subject,heads,body,signature) n = length(mails); n1 = length(heads); if n~=n1 error('number of heads must be equal to number of mails...'); end nb = length(body); if and(nb~=1,nb~=n) error('number of bodies must be equal to 1 or equal to number of mails...'); end ns = length(subject); if and(ns~=1,ns~=n) error('number of subjects must be equal to 1 or equal to number of mails...'); end if nb==1 msg = body; end if ns==1 sbj = char(subject); end for i=1:n if nb>1 msg = body{i}; end if ns>1 sbj = char(subject{i}); end Bio_sendmail(mymail,mypassword,mails{i},sbj,[heads{i} ' ' msg ' ' signature]); end
github
domingomery/Balu-master
Bio_labelregion.m
.m
Balu-master/InputOutput/Bio_labelregion.m
2,719
utf_8
cd7f29d456b55ec1242ce4df66773c05
% [d,D] = Bio_labelregion(I,L,c) % % Toolbox: Balu % User interface to label regions of an image. % % I is the original image (color or grayvalue). % L is a labeled image that indicates the segmented regions of I. % c is the maximal number of classes. % d(i) will be the class number of region i. % D is a binary image with the corresponding labels. % % Example: % I = imread('rice.png'); % I = I(1:70,1:70); % input image % [L,m] = Bim_segmowgli(I,ones(size(I)),40,1.5); % segmented image % [d,D] = Bio_labelregion(I,L,3); % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % function [d,D] = Bio_labelregion(I,L,c) if size(I,3)==3 J = rgb2gray(I); else J = I; end close all cmap = [0 0 1 0 1 0 1 0 0 0 1 1 1 0 1 1 1 0 0 0 0 1 1 1]; cmap = [cmap;cmap;cmap]; figure(2) Icol = []; for i=1:c Icol = [Icol;ones(20,20)*i]; end imshow(Icol,cmap) hold on for i=1:c text(5,i*20-10,num2str(i)) end title('Label color') colorstr = 'bgrcmykwbgrcmykwbgrcmykw'; warning off figure(1) subplot(1,2,2) imshow(I,[]) title('Original image') hold on n = max(max(L)); d = zeros(n,1); i = 1; D = zeros(size(J)); while(i<=n) R = zeros(size(J)); kk = find(L==i); R(kk) = 1; E = bwperim(R,4); %subplot(2,2,3) %Bio_edgeview(J,E); %title('Class label?') %figure(3) subplot(1,2,1) Bio_edgeview(J,R,[1 1 0]); title('Class label of yellow region?') ok = 0; while(not(ok)) r = input(sprintf('Region %3d/%3d: Class label? (1... %d) or -1 to correct previous: ',i,n,c)); % r = input(['Class label? (1...' num2str(c) ') or -1 to correct previous: ']); r = round(r); if not(isempty(r)) if (r==-1) i = max(i-2,0); ok = 1; disp('Correction: enter new choise...') end if (r>=1) && (r<=c) d(i) = r; D(kk) = r; ok = 1; [ii,jj] = find(R==1); x1 = max(jj); x2 = min(jj); y1 = max(ii); y2 = min(ii); subplot(1,2,2) plot([x1 x1 x2 x2 x1],[y1 y2 y2 y1 y1],colorstr(r)); title('Labeled regions') end end if (ok==0) beep end end i = i + 1; end Dc = D+1; map = [0 0 0;cmap]; subplot(1,2,2) imshow(Dc,map); subplot(1,2,1) Bio_edgeview(J,zeros(size(J)),[1 1 0]); title('Original image')
github
domingomery/Balu-master
Bio_loadimg.m
.m
Balu-master/InputOutput/Bio_loadimg.m
4,338
utf_8
a0434706346aa5c8206980dd19f0403b
% I = Bloadimg(f,i) % % Toolbox: Balu % % Load image i of set image defined by structure f % % f.path : directory where are the files % f.extension : extension (eg: 'jpg') % f.prefix : prefix (eg: 'DSC_') % f.digits : number of digits (eg:4) % f.gray : 1 means rgb to gray conversion % f.subsample : subsampling rate (eg:1 means no subsample) % f.resize : parameter of imresize, 0 means no imresize % f.window : image window % f.negative : negative window % f.sequence : if seq = [3 2 1], the image for i=1 will be No. 3 % f.imgmin : minimal number of the images (not used by Bloadimg) % f.imgmax : maximal number of the images (not used by Bloadimg) % f.show : 1 means display image (deafult = 0) % % Example: % f.path = ''; % Balu directory as path or current directory % f.extension = '.jpg'; % f.prefix = 'testimg'; % f.digits = 1; % f.gray = 1; % f.subsample = 1; % f.resize = 0; % f.window = []; % f.negative = 0; % f.sequence = 1:6; % f.imgmin = 1; % f.imgmax = 6; % I = Bloadimg(f,3); % imshow(I,[]) % % See Bseq_show. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [I,st] = Bio_loadimg(f,i) ipath = f.path; iext = f.extension; ipre = f.prefix; if isfield(f,'resize') re = f.resize; else re = 0; end if isfield(f,'subsample') t = f.subsample; else t = 1; end if isfield(f,'show') show = f.show; else show = 0; end if isfield(f,'window') w = f.window; else w = []; end if isfield(f,'negative') neg = f.negative; else neg = 0; end if isfield(f,'gray') gr = f.gray; else gr = 0; end if isfield(f,'sequence') seq = f.sequence; else seq = f.imgmin:f.imgmax; end if ~isempty(ipath) if ipath(end)~='/' ipath = [ipath '/']; end end %try % I = f.images(:,:,f.sequence(i)-f.imgmin+1); % %catch exception if isfield(f,'images') I = f.images(:,:,f.sequence(i)-f.imgmin+1); % I = f.images(:,:,i-f.imgmin+1); st = 'from memory'; else if show fprintf('Loading image %d...',i); end if ipre == '*' if iext(1)=='.' iext = iext(2:end); end dfiles = [dir([ipath '*.' lower(iext)]); dir([ipath '*.' upper(iext)])]; %tf = cat(1,dfiles.name); %[tj,ti] = sort(tf); ti = 1:length(dfiles); if (i>0)&&(i<=length(dfiles)) st = [ipath dfiles(ti(i)).name]; if ~exist(st,'file') error('file %s does not exist.',ipath) end if compare(upper(iext),'.MAT')==0 st(end-2:end) = 'mat'; s = ['load ' st]; eval(s); else I = imread(st); if show disp(st) end end else st = -1; if i==0 I = length(tf); else I = -1; end end else % if iext(1)~='.' % iext = ['.' iext] % end d = f.digits; sti = sprintf('0000000%d',seq(i)); sti = sti(end-d+1:end); st = sprintf('%s%s%s%s',ipath,ipre,sti,iext); if (exist(st,'file')) if compare(upper(iext),'.MAT')==0 st(end-2:end) = 'mat'; s = ['load ' st]; eval(s); else I = imread(st); if show disp(st) end end else I = -1; fprintf('%s does not exist.\n',st) end end if length(I(:))>1 if ~isempty(w) I = I(w(1):w(2),w(3):w(4),:); end if size(I,3)==3 if gr I = rgb2gray(I(1:t:end,1:t:end,:)); else I = I(1:t:end,1:t:end,:); end else I = I(1:t:end,1:t:end,:); end if neg I = 256.0-double(I); end end I = double(I); if re>0 I = imresize(I,re); end if show imshow(I/256,[]) end end
github
domingomery/Balu-master
Bio_latextable.m
.m
Balu-master/InputOutput/Bio_latextable.m
1,315
utf_8
39dd12c1612493fcdb51ecf1126a51f8
%function Bio_latextable(row_names,col_names,fmt,T) % % Toolbox: Balu % Code for a latex table. % % row_names is a cell with the names of the rows. % col_names is a cell with the names of the columns. % fmt is a cell with the format of each column. % T is the table. % % Example: % % col_names = {'cols','col 1','col 2','col 3','col4'}; % row_names = {'row 1','row 2','row 3'}; % fmt = {'%5.2f','%6.4f','%3.1f','%7.4f'}; % T = rand(3,4); % Bio_latextable(row_names,col_names,fmt,T) % % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % function Bio_latextable(row_names,col_names,fmt,T) disp('%') disp('% Latex code starts here:') disp('%') [N,M] = size(T); s = char(ones(M+1,1)*' c ')'; fprintf('\\begin{table}\n') fprintf('\\caption{Please write caption here.}\n') fprintf('\\begin{center}\n'); fprintf('\\begin{tabular}{ %s }\n',s(:)); fprintf('\\hline\n'); for j=1:M fprintf(' %s &',col_names{j}); end fprintf(' %s \\\\\n',col_names{M+1}); fprintf('\\hline\n'); for i=1:N fprintf(' %s ',row_names{i}); for j=1:M s = ['fprintf(' char(39) ' & ' fmt{j} char(39) ',T(i,j));']; eval(s); end fprintf('\\\\\n'); end fprintf('\\hline\n'); fprintf('\\end{tabular}\n'); fprintf('\\label{Tab:LABEL}\n'); fprintf('\\end{center}\n'); fprintf('\\end{table}\n');
github
domingomery/Balu-master
Bsq_trifocal.m
.m
Balu-master/SequenceProcessing/Bsq_trifocal.m
1,511
utf_8
88e029db5882015f7975ae21b960c995
% F = Bsq_trifocal(P) % % Toolbox: Balu % % Trifocal tesonsors of a sequence. % % P includes the projection matrices of n views as follows: % Projection Pk = P(k*3-2:k*3,:), for k=1,...,n % % T are the fundamental matrices stored as follows: % T(p,q,r,:) are the trifocal tensors (as 27x1 vector) between views p, % q and r for p=1:n-2, q=1:p+1:n-1, r=q+1:n % % Example: % % P1 = rand(3,4); % proyection matrix for view 1 % P2 = rand(3,4); % proyection matrix for view 2 % P3 = rand(3,4); % proyection matrix for view 3 % P4 = rand(3,4); % proyection matrix for view 4 % P5 = rand(3,4); % proyection matrix for view 4 % P6 = rand(3,4); % proyection matrix for view 4 % P = [P1;P2;P3;P4;P5;P6]; % all projection matrices % T = Bsq_trifocal(P); % fundamental matrices % T136 = zeros(3,3,3); % T136(:) = T(1,3,6,:) % Trifocal tensors between views 1-3-6 % % See also Bmv_fundamental, Bmv_trifocal, Bsq_fundamental. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function T = Bsq_trifocal(P) mg = size(P,1)/3; T = zeros(mg,mg,mg,27); for p=1:mg-2 p0 = 3*p-2; Pp = P(p0:p0+2,:); for q=p+1:mg-1 q0 = 3*q-2; Pq = P(q0:q0+2,:); for r=q+1:mg r0 = 3*r-2; Pr = P(r0:r0+2,:); Tpqr = Bmv_trifocal(Pp,Pq,Pr); T(p,q,r,:) = Tpqr(:)'; end end end
github
domingomery/Balu-master
Bsq_visualvoc.m
.m
Balu-master/SequenceProcessing/Bsq_visualvoc.m
4,045
utf_8
3cba9b1709bf6c98fe60dd585555a665
% From Spyrou et al 2010: % ... most of the cmmon visual words, i.e., those with smallest iDF values, % are not descriminative and their abscence would facilitate the retrieval % process. On the other hand, the rarest visual words are in most of the % cases as result of noise and may distract the retrieval process. To % overcome those problems, a stop list is created that includes the most % and the least frequent visual words of the image collection. % % From Sivic & Zisserman (2003): % Using a stop list the most frequent visual words that occur in almost all % images are supressed. The top 5% (of the frequency of visual words over % all the keyframes) and bottom 10% are stopped. % % Term Frequency-Inverse Document Frequency Weighting % After Sivic & Zisserman (PAMI 2009). See Section 4.1 % Each image of the training database is one 'document' % The words of each document will be filtered out using a stop list % (see program asr_stoplist.m). % % D.Mery, Notre Dame (2014) function opvoc = Bsq_visualvoc(Y,options) top_bound = options.top_bound; % eg. 0.05 top : most frequent word to be stopped bottom_bound = options.bottom_bound; % eg. 0.10 bottom : less frequent word to be stopped NV = options.NV; % number of visual words ixn = options.ixn; % indices of Y rows per document ii_top = round(NV*(1-top_bound))+1:NV; ii_bottom = 1:round(NV*bottom_bound); ii_stop = [ii_bottom ii_top]; show = options.show; if isfield(options,'newdictionary'); newdictionary = options.newdictionary; else newdictionary = 1; end if newdictionary == 1 if show>0 fprintf(' computing visual vocabulary from (%dx%d) with %d visual words...',size(Y,1),size(Y,2),NV); tic end % [opvoc.voc,opvoc.ix_voc] = vl_kmeans(Y',NV,'Algorithm','Elkan'); [opvoc.voc,opvoc.ix_voc] = vl_kmeans(Y',NV,'Algorithm','Elkan','NumRepetitions',3); if show>0 t = toc; fprintf('in %f sec.\n',t); end else fprintf('Using pre-computed vocabulary with %d visual words...\n',NV); end ww = double(opvoc.ix_voc); N = max(ixn); % # documents in the whole database nid = zeros(N,NV); % nid(d,i) # occurences of word i in document d ii = 1:NV; % indices of the words of the vocabulary for d=1:N dd = ixn==d; % indices of words in Y of document d ww_d = ww(dd); nid(d,:) = hist(ww_d,ii); % # occurrences of word i=1...NV in document d end % term frequency nid(d,i) = number of occurences of word i in document d, d=1,...k, t=1,...NV Ni = sum(nid>0); % document frequency (Ni(i) = # of documents in the collection containing word i, i=1,...NV) [sNi,jj] = sort(Ni); opvoc.i_stop = jj(ii_stop); opvoc.i_go = jj; opvoc.i_go(ii_stop) = []; opvoc.i_stop = sort(opvoc.i_stop); opvoc.i_go = sort(opvoc.i_go); opvoc.kd_voc = vl_kdtreebuild(opvoc.voc); opvoc.kd_go = vl_kdtreebuild(opvoc.i_go); opvoc.voc_stop = opvoc.voc(:,opvoc.i_stop); opvoc.voc_go = opvoc.voc(:,opvoc.i_go); opvoc.Ni = Ni; Ni(opvoc.i_stop) = 0; opvoc.Ni_go = Ni; nid_go = nid; nid_go(:,opvoc.i_stop) = 0; if options.tfidf > 0 % The following steps are necessary to create a stop list % the frequencies are computed after eliminating the stop words nd = sum(nid_go,2); % nd(d): # documents in document d (stop list words are not included) iDF = log(double(N)./(double(Ni)+1e-20)); opvoc.Vd = Bft_uninorm((nid_go./(nd*ones(1,NV))).*(ones(N,1)*iDF)); end % similar to Fig. 5 of Sivic & Zisserman (2003) if show>2 figure(12);clf; subplot(1,2,1); mesh(nid); subplot(1,2,2);plot(sNi);ax=axis; hold on plot([min(ii_top) min(ii_top)] ,[ax(3) ax(4)],'r:') plot([max(ii_bottom) max(ii_bottom)],[ax(3) ax(4)],'r:') end
github
domingomery/Balu-master
Bsq_vocabulary.m
.m
Balu-master/SequenceProcessing/Bsq_vocabulary.m
3,004
utf_8
4b7cf03feea650d98100b5670be8eb4f
% [v,Xcen,H] = Bsq_vocabulary(kp,V,options) % % Toolbox: Balu % % Visual vocabulary. % % kp.des is the descriptions of the keypoint. % kp.img is a vector containing the number of the image of each keypoint. % The minimum value of img is allways 1 and the maximum is the number of % processed images, i.e., f.imgmax-f.imgmin+1. % V is the number of visual words (clusters). % options.show display results. % % v is the document representation using "term frequency-inverse % document frequency" % Xcen are the centroids of the kmeans. % H are the histograms. % % % Reference: % Sivic & Zisserman: Efficient visual search for videos cast as text % retrieval. 31(4):591-606. PAMI 2009. % % Example: % f.path = ''; % Balu directory as path or current directory % f.extension = '.jpg'; % f.prefix = 'testimg'; % f.digits = 1; % f.gray = 1; % f.subsample = 1; % f.resize = [256 256]; % f.window = []; % f.negative = 0; % f.sequence = 1:6; % f.imgmin = 1; % f.imgmax = 6; % options.show = 1; % options.descriptor = 'sift'; % options.clean = 0; % kp = Bsq_des(f,options); % [v,Xcen,H] = Bsq_vocabulary(kp,100,options); % % See also Bsq_vgoogle, Bsq_sort. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [v,Xcen,H,Vnew,kd,N,Ni,Xcen_old,jsel] = Bsq_vocabulary(kp,V,options) if ~exist('options','var') options.show = 0; end if ~isfield(options,'tfidf') options.tfidf = 1; end if ~isfield(kp,'img') kp.img = ones(size(kp.des),1); end if ~isfield(options,'show') options.show = 0; end show = options.show; if show fprintf('Bsq_vocabul: Vector Quantization with %d clusters...\n',V) end X = single(kp.des); Xcen = (vl_kmeans(X',V,'Algorithm','ANN'))'; Xcen_old = Xcen; if show disp('Bsq_vocabul: building kd-tree...') pause(0) end kd = vl_kdtreebuild(Xcen'); H = []; Vnew = V; v = []; if options.tfidf == 1 N = max(kp.img); H = zeros(N,V); Nd = zeros(N,1); for d=1:N h = zeros(1,V); if show fprintf('Bsq_vocabul: processing image %d\n',d); end ii = find(kp.img==d); if ~isempty(ii) Xt = single(kp.des(ii,:)); j = vl_kdtreequery(kd,Xcen',Xt','NumNeighbors',1)'; nd = length(j); Nd(d) = nd; for k=1:nd; h(j(k))=h(j(k))+1; end H(d,:) = h; end end H1 = H>0; hs = mean(H1); j = hs>0.85; H(:,j) = []; jsel = not(j); Xcen(j,:) = []; V = size(H,2); v = zeros(N,V); Ni = sum(H>0,1); for d=1:N nd = Nd(d); if (nd>0) for i=1:V nid = H(d,i); ti = nid/nd*log(N/Ni(i)); v(d,i) = ti; end end end Vnew = V; end
github
domingomery/Balu-master
Bsq_fundamentalSIFT.m
.m
Balu-master/SequenceProcessing/Bsq_fundamentalSIFT.m
1,957
utf_8
de93354fcb011af6860d6243c67be119
% function [Fpq,Bpq] = Bsq_fundamentalSIFT(kp,p,q) % % Toolbox: Balu % % Fundamental matrix between two views p and q of a sequence using SIFT % descriptors kp. % % Example: case when keypoints must be extracted % % f.path = ''; % Balu directory as path or current directory % f.extension = '.png'; % f.prefix = 'X'; % f.digits = 1; % f.gray = 1; % f.subsample = 1; % f.resize = 0; % f.window = []; % f.negative = 0; % f.sequence = 1:6; % f.imgmin = 1; % f.imgmax = 6; % options.show = 1; % options.descriptor = 'harris+sift'; % options.clean = 0; % kp = Bsq_des(f,options); % F13 = Bsq_fundamentalSIFT(kp,1,3); % F14 = Bsq_fundamentalSIFT(kp,1,4); % figure(1); Bio_imgshow(f,1,[]); hold on % figure(2); Bio_imgshow(f,3,[]); hold on % figure(3); Bio_imgshow(f,4,[]); hold on % while(1) % figure(1); % disp('click a point in Figure 1...') % click % p = vl_click; m1 = [p(2) p(1) 1]'; % plot(p(1),p(2),'g+') % figure(2) % Bmv_epiplot(F13,m1) % figure(3) % Bmv_epiplot(F14,m1) % end % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function [Fpq,Bpq] = Bsq_fundamentalSIFT(kp,p,q) img = kp.img; des = kp.des; fra = kp.fra; % Fundamental matrix for image p and q using SIFT matching and RANSAC ip = find(img==p); iq = find(img==q); dp = des(ip,:); dq = des(iq,:); frap = fra(ip,:); fraq = fra(iq,:); [matches, scores] = vl_ubcmatch(dp', dq'); ii = find(scores<17000); xp = frap(matches(1,ii),[2 1]); xq = fraq(matches(2,ii),[2 1]); [Fpq, i] = Bmv_fundamentalRANSAC(xp',xq'); inl = ii(i); matchp = matches(1,inl); matchq = matches(2,inl); Bpq = [ip(matchp) iq(matchq)];
github
domingomery/Balu-master
Bsq_movie.m
.m
Balu-master/SequenceProcessing/Bsq_movie.m
1,868
utf_8
40172c3d3a79e3c6b61ff0ff1899b605
% M = Bsq_show(f,map,k) % % Toolbox: Balu % % Display a movie of an image sequence defined by structure f. % % map is the map of the image, if not given will be used "[]". % % f.path : directory where are the files % f.extension : extension (eg: 'jpg') % f.prefix : prefix (eg: 'DSC_') % f.digits : number of digits (eg:4) % f.gray : 1 means rgb to gray conversion % f.subsample : subsampling rate (eg:1 means no subsample) % f.resize : parameter of imresize, 0 means no imresize % f.window : image window % f.negative : negative window % f.sequence : if seq = [3 2 1], the image for i=1 will be No. 3 % f.imgmin : minimal number of the images (not used by Bio_loadimg) % f.imgmax : maximal number of the images (not used by Bio_loadimg) % % Iseq is the output image with all images of the sequence. % % Example: % f.path = ''; % Balu directory as path or current directory % f.extension = '.jpg'; % f.prefix = 'testimg'; % f.digits = 1; % f.gray = 1; % f.subsample = 1; % f.resize = [100 100]; % f.window = []; % f.negative = 0; % f.sequence = 1:6; % f.imgmin = 1; % f.imgmax = 6; % M = Bsq_movie(f); % % See Bio_loadimg, Bsq_show, movie, getframe. % % (c) D.Mery, PUC-DCC, 2012 % http://dmery.ing.puc.cl function M = Bsq_movie(f,map,k) clf % M = []; j = 0; for i=f.imgmin:f.imgmax j = j+1; % s = f.sequence(i) s = i; II = Bio_loadimg(f,s); if exist('map','var') if exist('k','var') if k>0 imshow(k*II,map) end else imshow(II,map) end else imshow(II,[]) end M(j) = getframe; enterpause end % movie(M)
github
domingomery/Balu-master
Bsq_des.m
.m
Balu-master/SequenceProcessing/Bsq_des.m
9,491
utf_8
aab8368709486b1a39dd2a711d00ad9c
% kp = Bsq_des(f,options) % % Toolbox: Balu % % Description of a sequence. % % f is the structure that defines the sequence % % f.path : directory where are the files % f.extension : extension (eg: 'jpg') % f.prefix : prefix (eg: 'DSC_') % f.digits : number of digits (eg:4) % f.gray : 1 means rgb to gray conversion % f.subsample : subsampling rate (eg:1 means no subsample) % f.resize : parameter of imresize, 0 means no imresize % f.window : image window % f.negative : negative window % f.sequence : if seq = [3 2 1], the image for i=1 will be No. 3 % f.imgmin : minimal number of the images (not used by Bio_loadimg) % f.imgmax : maximal number of the images (not used by Bio_loadimg) % % options.descriptor can be: 'sift', 'surf', 'sift-plus', 'phow', % 'harris', 'harris-defects', 'harris+sift', 'mser', 'clp', % 'blops', 'clp+harris'. % % options.show display results % options.param are paremeters of the method (if any). % options.clean is the name of the function used to eliminate keypoints % outside of the object of interest, this function is a tailored % function and returns a binary image with '1' object and '0' background % options.clean = 0 means no cleaning % % kp (keypoints) is a structure with the following fields: % kp.fra and kp.des are the frames and descriptions of each keypoint. % kp.img is a vector containing the number of the image of each keypoint. % The minimum value of img is allways 1 and the maximum is the number of % processed images, i.e., f.imgmax-f.imgmin+1 % kp.ilu is a look up table of the real number of the images (see example). % % Example: % f.path = ''; % Balu directory as path or current directory % f.prefix = 'testimg'; % f.extension = '.jpg'; % f.digits = 1; % f.gray = 1; % f.subsample = 1; % f.resize = [256 256]; % f.window = []; % f.negative = 0; % f.sequence = 1:6; % f.imgmin = 5; % f.imgmax = 6; % options.show = 1; % options.descriptor = 'sift'; % options.clean = 0; % % kp = Bsq_des(f,options); % % % The frames and description of image 5 are: % % i = find(kp.ilu==5); % j = find(kp.img==i); % f5 = kp.fra(j,:); % d5 = kp.des(j,:); % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function kp = Bsq_des(f,options) imin = f.imgmin; % first image imax = f.imgmax; % last image i0 = 0; img = []; fra = []; des = []; ilu = []; show = options.show; method = lower(options.descriptor); for i=imin:imax if show fprintf('Bsq_des : processing image %5d...',i) end J = Bio_loadimg(f,i); if length(J(:))>1 i0 = i0+1; im = single(J); switch method case 'sift' [frames, descrs] = vl_sift(im) ; case 'surf' Options.verbose = false; Options.tresh=0.5; Options.octaves = 5; Options.init_sample = 2; Ipts=OpenSurf(J,Options); x = cat(1,Ipts.x); y = cat(1,Ipts.y); s = cat(1,Ipts.scale); o = cat(1,Ipts.orientation); frames = [x';y';s';o']; n = length(Ipts); descrs = zeros(64,n); descrs(:) = cat(1,Ipts.descriptor); % l = cat(1,Ipts.laplacian); % ii = l==0; ii = frames(3,:)<4; frames = frames(:,ii); descrs = descrs(:,ii); case 'sift-plus' H = vl_harris( vl_imsmooth(J,3),7); idx = vl_localmax(H,0.3) ; [y,x] = ind2sub(size(im),idx); n = length(x); frames = [x; y; 20*ones(1,n);zeros(1,n)]; % [fhar2, dhar2] = vl_sift(im,'frames',frames) ; % [fsift, dsift] = vl_sift(im,'EdgeThresh',50) ; % frames = [fhar2 fsift]; % descrs = [dhar2 dsift]; [fhar2, dhar2] = vl_sift(im,'frames',frames) ; %[fsift, dsift] = vl_sift(im,'EdgeThresh',50) ; frames = [fhar2]; descrs = [dhar2]; case 'sifts' [frames, descrs] = BsiftmatchS(J,options.param.Iref,options.param.t1,options.param.t2,0) ; case 'phow' [frames, descrs] = vl_phow(im); case 'harris' H = vl_harris( vl_imsmooth(J,3),3); idx = vl_localmax(H ) ; [y,x] = ind2sub( size(im), idx ); n = length(x); frames = [x; y; 20*ones(1,n) ; zeros(1,n)]; [frames, descrs] = vl_sift(im,'frames',frames) ; case 'harris-defects' % p = [3 0.2 5 0.5 3]; p = [13 2 5 2 13]; J1 = vl_imsmooth(J,p(5)); im = single(J1); H = vl_harris(J1,p(1)); idx = vl_localmax(H,p(2)); [y1,x1] = ind2sub(size(im),idx); H = vl_harris(J,p(3)); idx = vl_localmax(H,p(4)); [y2,x2] = ind2sub(size(im),idx); x = [x1 x2]; y = [y1 y2]; n = length(x); frames = [x; y; 5*ones(1,n) ; zeros(1,n)]; [frames, descrs] = vl_sift(im,'frames',frames) ; case {'harris+sift','sift+harris'} H = vl_harris( vl_imsmooth(J,3),3); idx = vl_localmax(H) ; [y,x] = ind2sub(size(im),idx); n = length(x); frames = [x; y; 20*ones(1,n);zeros(1,n)]; [fhar2, dhar2] = vl_sift(im,'frames',frames); [fsift, dsift] = vl_sift(im) ; frames = [fhar2 fsift]; descrs = [dhar2 dsift]; case 'mser' [r,frames] = vl_mser(uint8(J),'MinDiversity',0.7,'MaxVariation',0.2,'Delta',10) ; % [r,frames] = vl_mser(uint8(J),'MinDiversity',options.param(1),'MaxVariation',options.param(2),'Delta',options.param(3)) ; frames = vl_ertr(frames) ; [frames, descrs] = vl_sift(im,'frames',frames(1:4,:)); case 'segmser' frames = Bim_segmser(J,options.param); [frames, descrs] = vl_sift(im,'frames',frames); case 'razor' frames = RazorDetector(J,options.param); if ~isempty(frames) [frames, descrs] = vl_sift(im,'frames',frames); end case 'gun' frames = GunDetector(J,options.param); if ~isempty(frames) [frames, descrs] = vl_sift(im,'frames',frames); end case 'clp' [Y,feat] = Bim_segdefects(J); n = size(feat,1); fclp = [feat(:,[2 1 3]) zeros(n,1)]'; [fclp, dclp] = vl_sift(im,'frames',fclp); frames = fclp; descrs = dclp; case 'blops' % options.param = [13 20 0 50 15 200 0.5 1.2]; % para la gillette % options.param = [17 15 0 100 15 2000 0 0]; % para la manzana [Y,feat] = Bim_segblops(J,options.param); n = size(feat,1); fblops = [feat(:,[2 1 3]) zeros(n,1)]'; [fblops, dblops] = vl_sift(im,'frames',fblops); frames = fblops; descrs = dblops; case 'clp+harris' H = vl_harris( vl_imsmooth(J,3),3); idx = vl_localmax(H) ; [y,x] = ind2sub(size(im),idx); n = length(x); frames = [x; y; 10*ones(1,n);zeros(1,n)]; [fhar1, dhar1] = vl_sift(im,'frames',frames) ; [Y,feat] = segdefects(J); n = size(feat,1); fclp = [feat(:,[2 1 3]) zeros(n,1)]'; [fclp, dclp] = vl_sift(im,'frames',fclp) ; [fsift, dsift] = vl_sift(im) ; frames = [fclp fhar1 fsift]; descrs = [dclp dhar1 dsift]; end if ~isfield(options,'clean') options.clean = 0; end if sum(options.clean) > 0 R = feval(options.clean,J); s = size(J); x = round(frames(1,:))'; y = round(frames(2,:))'; ix = sub2ind(s,y,x); t = R(ix); j = t==1; frames = frames(:,j); descrs = descrs(:,j); end if show clf imshow(J,[]); pause(0); x = frames(1,:); y = frames(2,:); hold on; plot(x,y,'.') fprintf('... %6d keypoints\n',length(x(:))) drawnow end if ~isempty(frames) fra = [fra; frames']; des = [des; descrs']; img = [img; i0*ones(size(frames,2),1)]; ilu = [ilu; i]; end else error('Bsq_des : image not found.'); end end kp.fra = fra; kp.des = des; kp.img = img; kp.ilu = ilu;
github
domingomery/Balu-master
Bsq_sort.m
.m
Balu-master/SequenceProcessing/Bsq_sort.m
4,689
utf_8
b7e6b7557c3924943e4e2fa32c851ce0
% s = Bsq_sort(kp,f,options) % [kp_new,files_new] = Bsq_sort(kp,files,options) % % Toolbox: Balu % % Sort an image sequence. % % f is the structure that defines the sequence % % f.path : directory where are the files % f.extension : extension (eg: 'jpg') % f.prefix : prefix (eg: 'DSC_') % f.digits : number of digits (eg:4) % f.gray : 1 means rgb to gray conversion % f.subsample : subsampling rate (eg:1 means no subsample) % f.resize : parameter of imresize, 0 means no imresize % f.window : image window % f.negative : negative window % f.sequence : if seq = [3 2 1], the image for i=1 will be No. 3 % f.imgmin : minimal number of the images (not used by Bloadimg) % f.imgmax : maximal number of the images (not used by Bloadimg) % % kp are the keypoints of the sequence (extracted with Bsq_des or any % similar procedure). If kp is empty the kypoints will be extracted with % Bsq_des using 'harris+sift' method (see help Bsq_des). % % options.show display results % options.indexonly 1: returns only s % options.indexonly 0: returns kp_new and files_new, they are the % corresponding keypoints and files sequence for the sorted images % % s is the sorted sequence. % % Example 1: case when keypoints must be extracted % % f.path = ''; % Balu directory as path or current directory % f.extension = '.png'; % f.prefix = 'X'; % f.digits = 1; % f.gray = 1; % f.subsample = 1; % f.resize = 0; % f.window = []; % f.negative = 0; % f.sequence = 1:6; % f.imgmin = 1; % f.imgmax = 6; % options.show = 1; % options.indexonly = 0; % options.descriptor = 'harris+sift'; % options.clean = 0; % [kp,f2] = Bsq_sort([],f,options); % Bsq_show(f); title('unsorted sequence') % figure % Bsq_show(f2); title('sorted sequence') % % % Example 2: case when keypoints are already extracted % % f.path = ''; % Balu directory as path or current directory % f.extension = '.png'; % f.prefix = 'X'; % f.digits = 1; % f.gray = 1; % f.subsample = 1; % f.resize = 0; % f.window = []; % f.negative = 0; % f.sequence = 1:6; % f.imgmin = 1; % f.imgmax = 6; % options.show = 1; % options.indexonly = 0; % options.descriptor = 'harris+sift'; % kp = Bsq_des(f,options); % figure % Bsq_show(f); title('unsorted sequence') % [kp2,f2] = Bsq_sort(kp,f,options); % figure % Bsq_show(f2); title('sorted sequence') % % Example 3: only the new indices are riquired % % f.path = ''; % Balu directory as path or current directory % f.extension = '.png'; % f.prefix = 'X'; % f.digits = 1; % f.gray = 1; % f.subsample = 1; % f.resize = 0; % f.window = []; % f.negative = 0; % f.sequence = 1:6; % f.imgmin = 1; % f.imgmax = 6; % options.show = 0; % options.indexonly = 1; % options.descriptor = 'harris+sift'; % kp = Bsq_des(f,options); % s = Bsq_sort([],f,options) % % See also Bsq_vgoogle, Bsq_des. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [kp_new,files_new] = Bsq_sort(kp,files,options) f = files; show = options.show; if isempty(kp) kp = Bsq_des(f,options); end v = Bsq_vocabulary(kp,200,options); n = max(kp.img); H = zeros(n,n); for i=1:n q = kp.ilu==(i+f.imgmin-1); vq = v(q,:)'; [rk,j] = Bfa_vecsimilarity(vq,v); H(i,j) = rk; end spmax = 0; for j=1:n i0 = j; sj = zeros(n,1); sj(1) = i0; w = ones(n,1); w(i0) = 0; sp = 0; for i=2:n h = w.*H(:,i0); [p,q] = max(h); i0 = q; sj(i) = q; w(q) = 0; sp = sp+p; end if sp>spmax spmax = sp; s = sj; end end if show figure Bsq_show(f);title('unsorted sequence') f.sequence(f.imgmin:f.imgmax) = s+f.imgmin-1; figure Bsq_show(f);title('sorted sequence') end if options.indexonly kp_new = s; files_new = (sum(H)-1)/(n-1); % confidence, small values are not similar enough else kp_new = kp; n = max(kp.img); for i=1:n ii = kp.img==s(i); kp_new.img(ii) = i; end files_new = f; files_new.sequence(files.imgmin:files.imgmax) = s+files.imgmin-1; end
github
domingomery/Balu-master
Bsq_load.m
.m
Balu-master/SequenceProcessing/Bsq_load.m
1,030
utf_8
d3512600879f06cd4d8637b6ccfbeb72
% f_new = Bsq_load(f) % % Toolbox: Balu % % Load an image sequence. % % f is a file structure (see Bio_loadimg for details) % % f_new includes a fild called f_new.images with an array NxMxm for a % sequence with NxM images % % Example: % f.path = ''; % Balu directory as path or current directory % f.extension = '.jpg'; % f.prefix = 'testimg'; % f.digits = 1; % f.gray = 1; % f.subsample = 1; % f.resize = 0; % f.window = []; % f.negative = 0; % f.sequence = 1:6; % f.imgmin = 1; % f.imgmax = 6; % f = Bsq_load(f); % Ij = f.images; % imshow(Ij(:,:,3),[]) % % See also Bload_img. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function f_new = Bsq_load(f) nimg = f.imgmax-f.imgmin+1; I = Bio_loadimg(f,f.imgmin); [N,M] = size(I); Ij = zeros(N,M,nimg); Ij(:,:,1) = I; for j=f.imgmin+1:f.imgmax Ij(:,:,j-f.imgmin+1) = Bio_loadimg(f,j); end f_new = f; f_new.images = Ij;
github
domingomery/Balu-master
Bsq_vgoogle.m
.m
Balu-master/SequenceProcessing/Bsq_vgoogle.m
2,607
utf_8
0362e101680bbe07d55060aa36e95924
% [rk,j] = Bsq_vgoogle(f,i,ilu,v,show) % % Toolbox: Balu % % Search sequence images similar to image i. % % f is the structure that defines the sequence % % f.path : directory where are the files % f.extension : extension (eg: 'jpg') % f.prefix : prefix (eg: 'DSC_') % f.digits : number of digits (eg:4) % f.gray : 1 means rgb to gray conversion % f.subsample : subsampling rate (eg:1 means no subsample) % f.resize : parameter of imresize, 0 means no imresize % f.window : image window % f.negative : negative window % f.sequence : if seq = [3 2 1], the image for i=1 will be No. 3 % f.imgmin : minimal number of the images (not used by Bio_loadimg) % f.imgmax : maximal number of the images (not used by Bio_loadimg) % % ilu is a look up table of the real number of the images (see example), % if ilu is empty ilu will be f.imgmin:f.imgmax. % v is the document representation using "term frequency-inverse % document frequency" % show display results % % Reference: % Sivic & Zisserman: Efficient visual search for videos cast as text % retrieval. 31(4):591-606. PAMI 2009. % % Example: % f.path = ''; % Balu directory as path or current directory % f.extension = '.jpg'; % f.prefix = 'testimg'; % f.digits = 1; % f.gray = 1; % f.subsample = 1; % f.resize = [256 256]; % f.window = []; % f.negative = 0; % f.sequence = 1:6; % f.imgmin = 1; % f.imgmax = 6; % options.show = 1; % options.descriptor = 'sift'; % options.clean = 0; % kp = Bsq_des(f,options); % v = Bsq_vocabulary(kp,100,options); % [rk,j] = Bsq_vgoogle(f,5,[],v,1); % similar images to image 5 % % See also Bsq_sort, Bsq_vocabulary. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [rk,j] = Bsq_vgoogle(f,i,ilu,v,show) if isempty(ilu) ilu = f.imgmin:f.imgmax; end vq = v(ilu==i,:)'; [rk,j] = Bfa_vecsimilarity(vq,v); if ~exist('show','var') show = 0; end if show disp('Finding similar images:') close all figure(1) imshow(Bio_loadimg(f,i),[]) title(sprintf('query image %d',i)) m = 4; for k=m+1:-1:2 figure(k) imshow(Bio_loadimg(f,ilu(j(k))),[]); s = sprintf('Figure %d: image %d (Similarity with image %d: %f)',k,ilu(j(k)),i,rk(k)); title(s) disp(s) end figure(1) disp('Figure 1: Query image') end
github
domingomery/Balu-master
Bsq_fundamental.m
.m
Balu-master/SequenceProcessing/Bsq_fundamental.m
1,824
utf_8
539819854dbc3fda7b210c7507b9989d
% F = Bsq_fundamental(P) % % Toolbox: Balu % % Fundamental matrices of a sequence. % % P includes the projection matrices of n views as follows: % Projection Pk = P(k*3-2:k*3,:), for k=1,...,n % % F are the fundamental matrices stored as follows: % F(p,q,:) is the Fundamental matrix (as 9x1 vector) between view p and % view q, for p=1:n-1 and q=1:p+1:n % % Example: % % M = [1 2 3 1]'; % 3D point (X=1,Y=2,Z=3) % P1 = rand(3,4); % proyection matrix for view 1 % P2 = rand(3,4); % proyection matrix for view 2 % P3 = rand(3,4); % proyection matrix for view 3 % P4 = rand(3,4); % proyection matrix for view 4 % m1 = P1*M; m1=m1/m1(3); % proyection point in view 1 % m2 = P2*M; m2=m2/m2(3); % proyection point in view 2 % m3 = P3*M; m3=m3/m3(3); % proyection point in view 3 % m4 = P4*M; m4=m4/m4(3); % proyection point in view 4 % P = [P1;P2;P3;P4]; % all projection matrices % F = Bsq_fundamental(P); % fundamental matrices % F13 = zeros(3,3); % F13(:) = F(1,3,:); % Fundamental matrix between views 1-3 % m3'*F13*m1 % epipolar constraint must be zero % F24 = zeros(3,3); % F24(:) = F(2,4,:); % Fundamental matrix between views 2-4 % m4'*F24*m2 % epipolar constraint must be zero % % See also Bmv_fundamental, Bmv_trifocal, Bsq_trifocal. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function F = Bsq_fundamental(P) n = size(P,1)/3; F = zeros(n,n,9); for p=1:n-1 i0 = 3*p-2; Pi = P(i0:i0+2,:); for q=p+1:n j0 = 3*q-2; Pj = P(j0:j0+2,:); Fij = Bmv_fundamental(Pi,Pj); F(p,q,:) = Fij(:)'; end end
github
domingomery/Balu-master
Bsq_multifundamental.m
.m
Balu-master/SequenceProcessing/Bsq_multifundamental.m
2,250
utf_8
1d51291e3817f5d620f4f0fc99afcf88
% function function [F,Bo] = Bsq_multifundamental(kp,options) % % Toolbox: Balu % % (No calibrated) Multiple fundamental matrices of a sequence % % Example: case when keypoints must be extracted % % f.path = ''; % Balu directory as path or current directory % f.extension = '.png'; % f.prefix = 'X'; % f.digits = 1; % f.gray = 1; % f.subsample = 1; % f.resize = 0; % f.window = []; % f.negative = 0; % f.sequence = 1:6; % f.imgmin = 1; % f.imgmax = 6; % % op1.show = 1; % op1.descriptor = 'harris+sift'; % op1.clean = 0; % op2.img1 = 1; % op2.img2 = 4; % op2.m = 3; % op2.show = 1; % % kp = Bsq_des(f,op1); % Fo = Bsq_fmulti(kp,op2); % ii = and(Fo(:,1)==1,Fo(:,2)==3); % F13 = zeros(3,3); F13(:) = Fo(ii,3:11); % ii = and(Fo(:,1)==1,Fo(:,2)==4); % F14 = zeros(3,3); F14(:) = Fo(ii,3:11); % % close all % figure(1); Bio_imgshow(f,1,[]); hold on % figure(2); Bio_imgshow(f,3,[]); hold on % figure(3); Bio_imgshow(f,4,[]); hold on % while(1) % figure(1); % disp('click a point in Figure 1...') % click % p = vl_click; m1 = [p(2) p(1) 1]'; % plot(p(1),p(2),'g+') % figure(2) % Bmv_epiplot(F13,m1); % figure(3) % Bmv_epiplot(F14,m1); % end % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function [F,Bo] = Bsq_multifundamental(kp,options) img1 = options.img1; img2 = options.img2; show = options.show; m = options.m; N = max(kp.img); F = zeros(10000,11); j = 0; Bo = zeros(20000,2); i = 1; if show disp('Computing Fundamental Matrices...') end for p = img1:img2 for q = p+1:min([p+m N]) j = j+1; if show fprintf('F(%d,%d)...',p,q) end [Fpq,Bpq] = Bsq_fundamentalSIFT(kp,p,q); F(j,:) = [p q Fpq(:)']; in = size(Bpq,1); Bo(i:i+in-1,:) = Bpq; i = i+in; end end F = F(1:j,:); Bo = Bo(1:i-1,:); if show fprintf('\n'); end
github
domingomery/Balu-master
Bsq_visualvoc_bak.m
.m
Balu-master/SequenceProcessing/Bsq_visualvoc_bak.m
4,007
utf_8
ad6bb77f38057b5193c205fc35b269ab
% From Spyrou et al 2010: % ... most of the cmmon visual words, i.e., those with smallest iDF values, % are not descriminative and their abscence would facilitate the retrieval % process. On the other hand, the rarest visual words are in most of the % cases as result of noise and may distract the retrieval process. To % overcome those problems, a stop list is created that includes the most % and the least frequent visual words of the image collection. % % From Sivic & Zisserman (2003): % Using a stop list the most frequent visual words that occur in almost all % images are supressed. The top 5% (of the frequency of visual words over % all the keyframes) and bottom 10% are stopped. % % Term Frequency-Inverse Document Frequency Weighting % After Sivic & Zisserman (PAMI 2009). See Section 4.1 % Each image of the training database is one 'document' % The words of each document will be filtered out using a stop list % (see program asr_stoplist.m). % % D.Mery, Notre Dame (2014) function options = Bsq_visualvoc(Y,options) top_bound = options.top_bound; % eg. 0.05 top : most frequent word to be stopped bottom_bound = options.bottom_bound; % eg. 0.10 bottom : less frequent word to be stopped NV = options.NV; % number of visual words ixn = options.ixn; % indices of Y rows per document ii_top = round(NV*(1-top_bound))+1:NV; ii_bottom = 1:round(NV*bottom_bound); ii_stop = [ii_bottom ii_top]; show = options.show; if isfield(options,'newdictionary'); newdictionary = options.newdictionary; else newdictionary = 1; end if newdictionary == 1 if show>0 fprintf(' computing visual vocabulary from (%dx%d) with %d visual words...',size(Y,1),size(Y,2),NV); tic end [options.voc,options.ix_voc] = vl_kmeans(Y',NV,'Algorithm','Elkan'); if show>0 t = toc; fprintf('in %f sec.\n',t); end else fprintf('Using pre-computed vocabulary with %d visual words...\n',NV); end ww = double(options.ix_voc); N = max(ixn); % # documents in the whole database nid = zeros(N,NV); % nid(d,i) # occurences of word i in document d ii = 1:NV; % indices of the words of the vocabulary for d=1:N dd = ixn==d; % indices of words in Y of document d ww_d = ww(dd); nid(d,:) = hist(ww_d,ii); % # occurrences of word i=1...NV in document d end % term frequency nid(d,i) = number of occurences of word i in document d, d=1,...k, t=1,...NV Ni = sum(nid>0); % document frequency (Ni(i) = # of documents in the collection containing word i, i=1,...NV) [sNi,jj] = sort(Ni); options.i_stop = jj(ii_stop); options.i_go = jj; options.i_go(ii_stop) = []; options.i_stop = sort(options.i_stop); options.i_go = sort(options.i_go); options.kd_voc = vl_kdtreebuild(options.voc); options.kd_go = vl_kdtreebuild(options.i_go); options.voc_stop = options.voc(:,options.i_stop); options.voc_go = options.voc(:,options.i_go); options.Ni = Ni; Ni(options.i_stop) = 0; options.Ni_go = Ni; nid_go = nid; nid_go(:,options.i_stop) = 0; if options.tfidf > 0 % The following steps are necessary to create a stop list % the frequencies are computed after eliminating the stop words nd = sum(nid_go,2); % nd(d): # documents in document d (stop list words are not included) iDF = log(double(N)./(double(Ni)+1e-20)); options.Vd = Bft_uninorm((nid_go./(nd*ones(1,NV))).*(ones(N,1)*iDF)); end % similar to Fig. 5 of Sivic & Zisserman (2003) if show>2 figure(12);clf; subplot(1,2,1); mesh(nid); subplot(1,2,2);plot(sNi);ax=axis; hold on plot([min(ii_top) min(ii_top)] ,[ax(3) ax(4)],'r:') plot([max(ii_bottom) max(ii_bottom)],[ax(3) ax(4)],'r:') end
github
domingomery/Balu-master
Bsq_show.m
.m
Balu-master/SequenceProcessing/Bsq_show.m
2,105
utf_8
a56ba86964f8832cd23477ff7ef1ece0
% Iseq = Bsq_show(f,n,map,k) % % Toolbox: Balu % % Display an image sequence defined by structure f. % % n is the number of images per row (default is the number of images of % the sequence). % % map is the map of the image, if not given will be used "[]". % % f.path : directory where are the files % f.extension : extension (eg: 'jpg') % f.prefix : prefix (eg: 'DSC_') % f.digits : number of digits (eg:4) % f.gray : 1 means rgb to gray conversion % f.subsample : subsampling rate (eg:1 means no subsample) % f.resize : parameter of imresize, 0 means no imresize % f.window : image window % f.negative : negative window % f.sequence : if seq = [3 2 1], the image for i=1 will be No. 3 % f.imgmin : minimal number of the images (not used by Bio_loadimg) % f.imgmax : maximal number of the images (not used by Bio_loadimg) % % Iseq is the output image with all images of the sequence. % % Example: % f.path = ''; % Balu directory as path or current directory % f.extension = '.jpg'; % f.prefix = 'testimg'; % f.digits = 1; % f.gray = 1; % f.subsample = 1; % f.resize = [100 100]; % f.window = []; % f.negative = 0; % f.sequence = 1:6; % f.imgmin = 1; % f.imgmax = 6; % Bsq_show(f,3); % % See Bio_loadimg. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function Iseq = Bsq_show(f,n,map,k) if (~exist('n','var')) n = f.imgmax-f.imgmin+1; end t = 0; II = []; Iseq = []; for i=f.imgmin:f.imgmax s = f.sequence(i); s = i; Ii = Bio_loadimg(f,s); Iseq = [Iseq Ii]; t = t + 1; if (t==n) II = [II; Iseq]; t = 0; Iseq = []; end end if t>0 Iseq = [Iseq zeros(size(Ii,1),size(Ii,2)*(n-t))]; II = [II; Iseq]; end Iseq = II; if exist('map','var') if exist('k','var') if k>0 imshow(k*II,map) end else imshow(II,map) end else imshow(II,[]) end
github
domingomery/Balu-master
Bsq_stoplist.m
.m
Balu-master/SequenceProcessing/Bsq_stoplist.m
2,649
utf_8
9e2d1e8f1699640d23b2f43116850843
% From Spyrou et al 2010: % ... most of the common visual words, i.e., those with smallest iDF values, % are not discriminative and their absence would facilitate the retrieval % process. On the other hand, the rarest visual words are in most of the % cases as result of noise and may distract the retrieval process. To % overcome those problems, a stop list is created that includes the most % and the least frequent visual words of the image collection. % % From Sivic & Zisserman (2003): % Using a stop list the most frequent visual words that occur in almost all % images are suppressed. The top 5% (of the frequency of visual words over % all the keyframes) and bottom 10% are stopped. function [Voc,ix,i_stop,i_go,kd,kd_go] = Bsq_stoplist(Y,options) top_bound = options.top_bound; % eg. 0.05 top : most frequent word to be stopped bottom_bound = options.bottom_bound; % eg. 0.10 bottom : less frequent word to be stopped NV = options.NV; % number of visual words ixn = options.ixn; % indices of Y rows per document ii_top = round(NV*(1-top_bound))+1:NV; ii_bottom = 1:round(NV*bottom_bound); ii_stop = [ii_bottom ii_top]; show = options.show; if isfield(options,'newdictionary'); newdictionary = options.newdictionary; else newdictionary = 1; end if newdictionary == 1 fprintf('Computing vocabulary of Y (%dx%d) with %d visual words...',size(Y,1),size(Y,2),NV); tic [Voc,ix] = vl_kmeans(Y',NV,'Algorithm','Elkan'); t = toc; fprintf('in %f sec.\n',t); else fprintf('Using pre-computed vocabulary with %d visual words...\n',NV); Voc = options.voc; ix = options.ix_voc; end ww = double(ix); N = max(ixn); TF = zeros(N,NV); for i=1:N ii = ixn==i; ww_i = ww(ii); TF(i,:) = hist(ww_i,1:NV); end % term frequency TF(d,t) = number of occurrences of word t in document d, d=1,...k, t=1,...NV DF = sum(TF>0); % document frequency (DF(t) = number of documents in the collection that contain a word t, t=1,...NV) % Not necessary to create a stop list % iDF = log(N./(DF)); % TFIDF = TF.*(ones(k,1)*iDF); % [ii,jj] = sort(iDF,'descend'); [~,jj] = sort(DF); i_stop = jj(ii_stop); i_go = jj; i_go(ii_stop) = []; kd = vl_kdtreebuild(Voc); kd_go = vl_kdtreebuild(i_go); % V_stop = Voc(:,j_stop); % V_go = Voc(:,j_go); % like Fig. 5 of Sivic & Zisserman (2003) if show figure(12);clf; subplot(1,3,1); mesh(TF); subplot(1,3,2);plot(sort(DF,'descend'));ax=axis; subplot(1,3,3);plot(sort(DF(i_go),'descend'));axis(ax) end
github
domingomery/Balu-master
Bfx_moments.m
.m
Balu-master/FeatureExtraction/Bfx_moments.m
1,948
utf_8
653e002ee885a61555adb5dd36829228
% [X,Xn] = Bfx_moments(R,options) % % Toolbox: Balu % % Extract moments and central moments. % % options.show = 1 display mesagges. % options.central = 1 for central moments, and 0 for normal moments % options.rs = n x 2 matrix that contains the indices of the % moments to be extracted (see example). % % X is vector that contains the n moments. % Xn is the list of the n feature names. % % Example (Centroid of a region) % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % imshow(R); % options.show = 1; % options.central = 0; % options.rs = [0 0; 1 0; 0 1]; % [X,Xn] = Bfx_moments(R,options); % ic = X(2)/X(1); % jc = X(3)/X(1); % hold on % plot(jc,ic,'rx') % % See also Bfx_basicgeo, Bfx_gupta, Bfx_fitellipse, Bfx_flusser, % Bfx_hugeo. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl function [X,Xn] = Bfx_moments(R,options) if ~exist('options','var') options.show = 0; end if options.show == 1 disp('--- extracting moments...'); end [Ireg,Jreg] = find(R==1); % pixels in the region A = length(Ireg); central = options.central; rs = options.rs; n = size(rs,1); if central i_m = mean(Ireg); j_m = mean(Jreg); I1 = Ireg - i_m*ones(A,1); J1 = Jreg - j_m*ones(A,1); strc = 'Central Moment'; else I1 = Ireg; J1 = Jreg; strc = 'Moment'; end X = zeros(1,n); Xn = char(zeros(n,24)); for i=1:n r = rs(i,1); s = rs(i,2); Ir = ones(A,1); Js = ones(A,1); if r>0 for jr = 1:r Ir = Ir.*I1; end end if s>0 for js = 1:s Js = Js.*J1; end end X(i) = Ir'*Js; str = [strc ' ' num2str(r) ',' num2str(s) ' ']; Xn(i,:) = str(1:24); end
github
domingomery/Balu-master
Bfx_basicint.m
.m
Balu-master/FeatureExtraction/Bfx_basicint.m
1,843
utf_8
04c161a3907d7c57c57632eb0fc9accd
% [X,Xn] = Bfx_basicint(I,R,options) % [X,Xn] = Bfx_basicint(I,options) % % Toolbox: Balu % Basic intensity features % % X is the features vector, Xn is the list feature names (see Example to % see how it works). % % Reference: % Kumar, A.; Pang, G.K.H. (2002): Defect detection in textured materials % using Gabor filters. IEEE Transactions on Industry Applications, % 38(2):425-440. % % Example: % options.mask = 5; % Gauss mask for gradient computation % options.show = 1; % display results % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % J = double(I(:,:,2))/256; % normalized green channel % [X,Xn] = Bfx_basicint(J,R,options); % basic intenisty features % Bio_printfeatures(X,Xn) % % See also Bfx_haralick, Bfx_clp, Bfx_gabor, Bfx_fourier, Bfx_dct, Bfx_lbp. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_basicint(I,R,options) if nargin==2; options = R; R = ones(size(I)); end if ~isfield(options,'mask') options.mask = 15; end if options.show disp('--- extracting basic intensity features...'); end E = bwperim(R,4); ii = find(R==1); jj = find(R==0, 1); kk = E==1; I = double(I); I1 = Bim_d1(I,options.mask); I2 = Bim_d2(I); if ~isempty(jj) C = mean(abs(I1(kk))); else C = -1; end J = I(ii); G = mean(J); S = std(J); K = kurtosis(J); Sk = skewness(J); D = mean(I2(ii)); X = [G S K Sk D C]; Xn = [ 'Intensity Mean ' 'Intensity StdDev ' 'Intensity Kurtosis ' 'Intensity Skewness ' 'Mean Laplacian ' 'Mean Boundary Gradient '];
github
domingomery/Balu-master
Bfx_onesift.m
.m
Balu-master/FeatureExtraction/Bfx_onesift.m
1,955
utf_8
c8fbe5fdc65eb5c2e40fbd368002f579
% [X,Xn,options] = Bfx_onesift(I,R,options) % [X,Xn,options] = Bfx_onesift(I,options) % [X,Xn] = Bfx_onesift(I,R,options) % [X,Xn] = Bfx_onesift(I,options) % % Toolbox: Balu % Extract only one SIFT descriptor of region R of image I. % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % R is a binary image or empty. If R is given the sift will be computed % in the region defined by the piexels where R==1. % % Output: % % References: % D. G. Lowe, Distinctive image features from scale-invariant % keypoints. IJCV, vol. 2, no. 60, pp. 91-110, 2004. % % A. Vedaldi, B. Fulkerson: VLFeat: An Open and Portable Library % of Computer Vision Algorithms, 2008 (http://www.vlfeat.org/) % % % Example 5: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 8; % number of neighbor samples % options.sk = 0.25; % angle sampling % options.weight = 9; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % weighted LBP features % bar(X) % histogram % See also Bfx_gabor, Bfx_clp, Bfx_fourier, Bfx_dct. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % function [X,Xn,options] = Bfx_onesift(I,R,options) %if nargin==2; % options = R; % R = ones(size(I)); %end if isempty(R) R = ones(size(I)); end [ii,jj] = find(R==1); ff = [mean(jj); mean(ii); sqrt(length(ii))/2; 0]; [ff,dd] = vl_sift(single(I),'Frames',ff); X = dd'; n = 128; Xn = char(zeros(n,24)); for k=1:n s = sprintf('SIFT(%d) ',k); Xn(k,:) = s(1:24); end
github
domingomery/Balu-master
Bfx_hugeo.m
.m
Balu-master/FeatureExtraction/Bfx_hugeo.m
2,304
utf_8
5e1a0fce78c514e4d097bc0f6941ba0e
% [X,Xn] = Bfx_hugeo(R) % [X,Xn] = Bfx_hugeo(R,options) % % Toolbox: Balu % % Extract the seven Hu moments from binary image R. % % options.show = 1 display mesagges. % % X is a 7 elements vector: % X(i): Hu-moment i for i=1,...,7. % Xn is the list of feature names. % % Reference: % Hu, M-K.: "Visual Pattern Recognition by Moment Invariants", % IRE Trans. Info. Theory IT-8:179-187: 1962. % % Example: % I = imread('testimg3.jpg'); % input image % R = Bim_segbalu(I); % segmentation % [L,n] = bwlabel(R); % regions % imshow(L,[]) % X = []; % for i=1:n % [Xi,Xn] = Bfx_hugeo(L==i); % Hu moments % X = [X;Xi]; % end % X % % See also Bfx_basicgeo, Bfx_gupta, Bfx_fitellipse, Bfx_flusser. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_hugeo(R,options) if ~exist('options','var') options.show = 0; end if options.show == 1 disp('--- extracting Hu moments...'); end [Ireg,Jreg] = find(R==1); % pixels in the region i_m = mean(Ireg); j_m = mean(Jreg); A = length(Ireg); I0 = ones(A,1); J0 = ones(A,1); I1 = Ireg - i_m*ones(A,1); J1 = Jreg - j_m*ones(A,1); I2 = I1.*I1; J2 = J1.*J1; I3 = I2.*I1; J3 = J2.*J1; % Central moments u00 = A; %u00 = m00 = (I0'*J0); u002 = u00*u00; u0025 = u00^2.5; % u0015 = u00^1.5; not used n02 = (I0'*J2)/u002; n20 = (I2'*J0)/u002; n11 = (I1'*J1)/u002; n12 = (I1'*J2)/u0025; n21 = (I2'*J1)/u0025; n03 = (I0'*J3)/u0025; n30 = (I3'*J0)/u0025; f1 = n20+n02; f2 = (n20-n02)^2 + 4*n11^2; f3 = (n30-3*n12)^2+(3*n21-n03)^2; f4 = (n30+n12)^2+(n21+n03)^2; f5 = (n30-3*n12)*(n30+n12)*((n30+n12)^2 - 3*(n21+n03)^2) + (3*n21-n03)*(n21+n03)*(3*(n30+n12)^2 - (n21+n03)^2); f6 = (n20-n02)*((n30+n12)^2 - (n21+n03)^2) + 4*n11*(n30+n12)*(n21+n03); f7 = (3*n21-n03)*(n30+n12)*((n30+n12)^2 - 3*(n21+n03)^2) - (n30-3*n12)*(n21+n03)*(3*(n30+n12)^2 - (n21+n03)^2); X = [f1 f2 f3 f4 f5 f6 f7]; Xn = [ 'Hu-moment 1 ' 'Hu-moment 2 ' 'Hu-moment 3 ' 'Hu-moment 4 ' 'Hu-moment 5 ' 'Hu-moment 6 ' 'Hu-moment 7 '];
github
domingomery/Balu-master
Bfx_hog.m
.m
Balu-master/FeatureExtraction/Bfx_hog.m
3,258
utf_8
a089b1fa3b7f1cb82642615fc6cf1c1f
% [X,Xn] = Bfx_hog(I,options) % % Toolbox: Balu % Histogram of Orientated Gradients features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % options.nj; : number of HOG windows per bound box % options.ni : in i (vertical) and j (horizaontal) direction % options.B : number of histogram bins % options.show : show histograms (glyphs) % % Example: % options.nj = 20; % 10 x 20 % options.ni = 10; % histograms % options.B = 9; % 9 bins % options.show = 1; % show results % I = imread('testimg1.jpg'); % input image % J = rgb2gray(I); % figure(1);imshow(J,[]); % figure(2); % [X,Xn] = Bfx_hog(J,options); % HOG features (see gradients % % arround perimeter). % % See also Bfx_phog, Bfx_lbp. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % function [X,Xn,options] = Bfx_hog(I,R,options) if nargin==2; options = R; R = ones(size(I)); end if ~isfield(options,'normalize') options.normalize = 0; end nj = options.nj; % number of HOG windows per bound box ni = options.ni; % in i (vertical) and j (horizaontal) direction B = options.B; % number of histogram bins show = options.show; % show histograms N = size(I,1); M = size(I,2); X = zeros(1,nj*ni*B); % column vector with zeros I = double(I); dj = floor(M/(nj+1)); di = floor(N/(ni+1)); t = 0; hj = [-1,0,1]; hi = -hj'; Gj = imfilter(I,hj); Gi = imfilter(I,hi); A = atan2(Gi,Gj); A = mod(A,pi); G = ((Gi.^2)+(Gj.^2)).^.5; K = 4*di*dj; ang = zeros(K,1); mag = zeros(K,1); if show J = zeros(N,M); ss = min([N/ni M/nj])*0.40; end w = zeros(ni,nj,B); for i = 1:ni ii = (i-1)*di+1:(i+1)*di; i0 = mean(ii); for j = 1:nj jj = (j-1)*dj+1:(j+1)*dj; j0 = mean(jj); t = t+1; ang(:) = A(ii,jj); mag(:) = G(ii,jj); X2 = zeros(B,1); for b = 1:B q = find(ang<=pi*b/B); X2(b) = X2(b)+sum(mag(q)); ang(q) = 5; end X2 = X2/(norm(X2)+0.01); X(1,indices(t,B)) = X2; % w(i,j,:) = X2; if show for b=1:B alpha = pi*b/B; q = -ss:ss; qi = round(i0+q*cos(alpha)); qj = round(j0+q*sin(alpha)); qk = qi+(qj-1)*N; J(qk) = J(qk)+X2(b); end J(round(i0),round(j0))=1; end end end if show imshow(round(J/max2(J)*256),jet) options.J = J; end options.w = w; Xn = char(zeros(nj*ni*B,24)); Xn(:,1) = 'H'; Xn(:,2) = 'O'; Xn(:,3) = 'G'; J = uint8(zeros(N,M,3)); G(G>363) = 363; % max2(Gi) = max2(Gi) = 256 => max2(G) = sqrt(2*256^2) J(:,:,1) = uint8(round(G/363*255)); J(:,:,2) = uint8(round(A/pi*255)); options.Ihog = J; if options.normalize X = X/sum(X); end
github
domingomery/Balu-master
Bfx_huint.m
.m
Balu-master/FeatureExtraction/Bfx_huint.m
2,385
utf_8
2d95567f2dde7180bc05e62ba3fdb92d
% [X,Xn,Xu] = Bfx_huint(I,R,options) % % Toolbox: Balu % Hu moments with intensity. % % X is a 7 elements vector: % X(i): Hu-moment i for i=1,...,7. % Xn is the list of feature names (see Example to see how it works). % % Reference: % Hu, M-K.: "Visual Pattern Recognition by Moment Invariants", % IRE Trans. Info. Theory IT-8:179-187: 1962. % % Example: % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % J = double(I(:,:,1))/256; % normalized red channel % options.show = 1; % display results % [X,Xn] = Bfx_huint(J,R,options); % Hu moments with intenisty % Bio_printfeatures(X,Xn) % % See also Bfx_haralick, Bfx_clp, Bfx_fourier, Bfx_dct, Bfx_lbp. % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_huint(I,R,options) if ~exist('options','var') options.show = 0; end if options.show == 1 disp('--- extracting Hu moments with intensity...'); end [Ireg,Jreg] = find(R==1); % pixels in the region im = mean(Ireg); jm = mean(Jreg); Kreg = R==1; A = length(Ireg); I0 = ones(A,1); J0 = ones(A,1); I1 = Ireg - im*ones(A,1); J1 = Jreg - jm*ones(A,1); I2 = I1.*I1; J2 = J1.*J1; I3 = I2.*I1; J3 = J2.*J1; xreg = I(Kreg); if (sum(xreg==0)) xreg = ones(A,1); end J0X = double(J0).*double(xreg); % Central moments u00 = (I0'*J0X); u002 = u00*u00; u0025 = u00^2.5; n02 = (I0'*J2)/u002; n20 = (I2'*J0)/u002; n11 = (I1'*J1)/u002; n12 = (I1'*J2)/u0025; n21 = (I2'*J1)/u0025; n03 = (I0'*J3)/u0025; n30 = (I3'*J0)/u0025; f1 = n20+n02; f2 = (n20-n02)^2 + 4*n11^2; f3 = (n30-3*n12)^2+(3*n21-n03)^2; f4 = (n30+n12)^2+(n21+n03)^2; f5 = (n30-3*n12)*(n30+n12)*((n30+n12)^2 - 3*(n21+n03)^2) + (3*n21-n03)*(n21+n03)*(3*(n30+n12)^2 - (n21+n03)^2); f6 = (n20-n02)*((n30+n12)^2 - (n21+n03)^2) + 4*n11*(n30+n12)*(n21+n03); f7 = (3*n21-n03)*(n30+n12)*((n30+n12)^2 - 3*(n21+n03)^2) - (n30-3*n12)*(n21+n03)*(3*(n30+n12)^2 - (n21+n03)^2); X = [f1 f2 f3 f4 f5 f6 f7]; Xn = [ 'Hu-moment-int 1 ' 'Hu-moment-int 2 ' 'Hu-moment-int 3 ' 'Hu-moment-int 4 ' 'Hu-moment-int 5 ' 'Hu-moment-int 6 ' 'Hu-moment-int 7 '];
github
domingomery/Balu-master
Bfx_lbpint.m
.m
Balu-master/FeatureExtraction/Bfx_lbpint.m
18,156
utf_8
58b30c959a0a79e86ffcf6369760e789
% [X,Xn,options] = Bfx_lbp(I,R,options) % [X,Xn,options] = Bfx_lbp(I,options) % [X,Xn] = Bfx_lbp(I,R,options) % [X,Xn] = Bfx_lbp(I,options) % % Toolbox: Balu % Local Binary Patterns features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % It calculates the LBP over the a regular grid of patches. The function % uses Heikkila & Ahonen (see http://www.cse.oulu.fi/MVG/Research/LBP). % % It returns a matrix of uniform lbp82 descriptors for I, made by % concatenating histograms of each grid cell in the image. % Grid size is options.hdiv * options.vdiv % % R is a binary image or empty. If R is given the lbp will be computed % the corresponding pixles R==0 in image I will be set to 0. % % Output: % X is a matrix of size ((hdiv*vdiv) x 59), each row has a % histogram corresponding to a grid cell. We use 59 bins. % options.x of size hdiv*vdiv is the x coordinates of center of ith grid cell % options.y of size hdiv*vdiv is the y coordinates of center of ith grid cell % Both coordinates are calculated as if image was a square of side length 1. % % References: % Ojala, T.; Pietikainen, M. & Maenpaa, T. Multiresolution gray-scale % and rotation invariant texture classification with local binary % patterns. IEEE Transactions on Pattern Analysis and Machine % Intelligence, 2002, 24, 971-987. % % Mu, Y. et al (2008): Discriminative Local Binary Patterns for Human % Detection in Personal Album. CVPR-2008. % % Example 1: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 0; % classic LBP % options.samples = 8; % number of neighbor samples % options.mappingtype = 'u2'; % uniform LBP % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % LBP features % bar(X) % histogram % % Example 2: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 0; % classic LBP % options.samples = 8; % number of neighbor samples % options.mappingtype = 'ri'; % rotation-invariant LBP % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % LBP features % bar(X) % histogram % % Example 3: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 8; % number of neighbor samples % options.sk = 0.5; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % semantic LBP features % bar(X) % histogram % % Example 4: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 16; % number of neighbor samples % options.sk = 0.5; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % semantic LBP features % bar(X) % histogram % % Example 5: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 8; % number of neighbor samples % options.sk = 0.25; % angle sampling % options.weight = 9; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % weighted LBP features % bar(X) % histogram % See also Bfx_gabor, Bfx_clp, Bfx_fourier, Bfx_dct. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % function [X,Xn,options] = Bfx_lbpint(I,R,options) if nargin==2; options = R; R = 1; end if ~isfield(options,'normalize') options.normalize = 0; end if ~isfield(options,'coor') i1 = 1; j1 = 1; i2 = size(I,1); j2 = size(I,2); else i1 = options.coor(1); j1 = options.coor(2); i2 = options.coor(3); j2 = options.coor(4); end desc = Bim_inthistread(I,i1,j1,i2,j2); % vdiv = options.vdiv; % hdiv = options.hdiv; % % if ~isfield(options,'show') % options.show = 0; % end % % if options.show == 1 % disp('--- extracting local binary patterns features...'); % end % % if ~isfield(options,'samples') % options.samples = 8; % end % % if ~isfield(options,'radius') % options.radius = log(options.samples)/log(2)-1; % end % % if ~isfield(options,'semantic') % options.semantic = 0; % end % % if ~isfield(options,'weight') % options.weight = 0; % end LBPst = 'LBP'; st = 'int'; % if options.semantic>0 % if ~isfield(options,'sk') % options.sk = 1; % end % mapping = getsmapping(options.samples,options.sk); % LBPst = ['s' LBPst]; % st='8x8'; % else % % mapping = getmapping(8,'u2'); % if ~isfield(options,'mappingtype') % options.mappingtype = 'u2'; % end % st = sprintf('%d,%s',options.samples,options.mappingtype); % mapping = getmapping(options.samples,options.mappingtype); % end % get lbp image % if ~isempty(R); % I(R==0) = 0; % end code_img = I; [n1,n2] = size(code_img); % [N,M] = size(I); % Ilbp = zeros(size(I)); % i1 = round((N-n1)/2); % j1 = round((M-n2)/2); % code_img = Ilbp(i1+1:i1+n1,j1+1:j1+n2); % options.Ilbp = Ilbp; %ylen = round(n1/vdiv); %xlen = round(n2/hdiv); % split image into blocks (saved as columns) %grid_img = im2col(code_img,[ylen, xlen], 'distinct'); grid_img = code_img(:); % if options.weight>0 % LBPst = ['w' LBPst]; % mt = 2*options.radius-1; % mt2 = mt^2; % Id = double(I); % switch options.weight % case 1 % W = abs(conv2(Id,ones(mt,mt)/mt2,'same')-Id); % case 2 % W = (abs(conv2(Id,ones(mt,mt)/mt2,'same')-Id))./(Id+1); % case 3 % W = abs(medfilt2(Id,[mt mt])-Id); % case 4 % W = abs(medfilt2(Id,[mt mt])-Id)./(Id+1); % case 5 % W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id); % case 6 % W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id)./(Id+1); % case 7 % Id = conv2(Id,ones(mt,mt)/mt2,'same'); % W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id)./(Id+1); % case 8 % Id = medfilt2(Id,[mt mt]); % W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id)./(Id+1); % case 9 % Id = medfilt2(Id,[mt mt]); % W = abs(ordfilt2(Id,mt2-1,ones(mt,mt))-Id)./(Id+1); % otherwise % error('Bfx_lbp does not recognice options.weight = %d.',options.weight); % end % W = W(mt+1:end-mt,mt+1:end-mt); % grid_W = im2col(W,[ylen, xlen], 'distinct'); % nwi = mapping.num; % nwj = size(grid_W,2); % nwk = size(grid_W,1); % desc = zeros(nwi,nwj); % for j=1:nwj % x = grid_img(:,j)+1; % y = grid_W(:,j); % d = zeros(nwi,1); % for k=1:nwk % d(x(k))=d(x(k))+y(k); % % d(x(k))=d(x(k))+1; % normal LBP each LBP has equal weight % end % desc(:,j) = d; % end % % else % desc = hist(double(grid_img), 0:options.maxD-1); % calculate coordinates of descriptors as if I was square w/ side=1 %end %dx = 1.0/hdiv; %dy = 1.0/vdiv; dx = 1; dy = 1; x = dx/2.0: dx :1.0-dx/2.0; y = dy/2.0: dy :1.0-dy/2.0; options.x = x; options.y = y; %if hdiv*vdiv>1 % D = desc'; %else X = desc; if options.normalize X = X/sum(X); end %end [M,N] = size(X); Xn = char(zeros(N*M,24)); % X = zeros(1,N*M); % k=0; % for i=1:M % for j=1:N % k = k+1; % s = sprintf('%s(%d,%d)[%s] ',LBPst,i,j,st); % Xn(k,:) = s(1:24); % X(k) = D(i,j); % end % end end %GETMAPPING returns a structure containing a mapping table for LBP codes. % MAPPING = GETMAPPING(SAMPLES,MAPPINGTYPE) returns a % structure containing a mapping table for % LBP codes in a neighbourhood of SAMPLES sampling % points. Possible values for MAPPINGTYPE are % 'u2' for uniform LBP % 'ri' for rotation-invariant LBP % 'riu2' for uniform rotation-invariant LBP. % % Example: % I=imread('rice.tif'); % MAPPING=getmapping(16,'riu2'); % LBPHIST=lbp(I,2,16,MAPPING,'hist'); % Now LBPHIST contains a rotation-invariant uniform LBP % histogram in a (16,2) neighbourhood. % function mapping = getmapping(samples,mappingtype) % Version 0.1.1 % Authors: Marko Heikkila and Timo Ahonen % Changelog % 0.1.1 Changed output to be a structure % Fixed a bug causing out of memory errors when generating rotation % invariant mappings with high number of sampling points. % Lauge Sorensen is acknowledged for spotting this problem. table = 0:2^samples-1; newMax = 0; %number of patterns in the resulting LBP code index = 0; if strcmp(mappingtype,'u2') %Uniform 2 newMax = samples*(samples-1) + 3; for i = 0:2^samples-1 j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate left numt = sum(bitget(bitxor(i,j),1:samples)); %number of 1->0 and %0->1 transitions %in binary string %x is equal to the %number of 1-bits in %XOR(x,Rotate left(x)) if numt <= 2 table(i+1) = index; index = index + 1; else table(i+1) = newMax - 1; end end end if strcmp(mappingtype,'ri') %Rotation invariant tmpMap = zeros(2^samples,1) - 1; for i = 0:2^samples-1 rm = i; r = i; for j = 1:samples-1 r = bitset(bitshift(r,1,samples),1,bitget(r,samples)); %rotate %left if r < rm rm = r; end end if tmpMap(rm+1) < 0 tmpMap(rm+1) = newMax; newMax = newMax + 1; end table(i+1) = tmpMap(rm+1); end end if strcmp(mappingtype,'riu2') %Uniform & Rotation invariant newMax = samples + 2; for i = 0:2^samples - 1 j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate left numt = sum(bitget(bitxor(i,j),1:samples)); if numt <= 2 table(i+1) = sum(bitget(i,1:samples)); else table(i+1) = samples+1; end end end mapping.table=table; mapping.samples=samples; mapping.num=newMax; end % LBP returns the local binary pattern image or LBP histogram of an image. % J = LBP(I,R,N,MAPPING,MODE) returns either a local binary pattern % coded image or the local binary pattern histogram of an intensity % image I. The LBP codes are computed using N sampling points on a % circle of radius R and using mapping table defined by MAPPING. % See the getmapping function for different mappings and use 0 for % no mapping. Possible values for MODE are % 'h' or 'hist' to get a histogram of LBP codes % 'nh' to get a normalized histogram % Otherwise an LBP code image is returned. % % J = LBP(I) returns the original (basic) LBP histogram of image I % % J = LBP(I,SP,MAPPING,MODE) computes the LBP codes using n sampling % points defined in (n * 2) matrix SP. The sampling points should be % defined around the origin (coordinates (0,0)). % % Examples % -------- % I=imread('rice.png'); % mapping=getmapping(8,'u2'); % H1=LBP(I,1,8,mapping,'h'); %LBP histogram in (8,1) neighborhood % %using uniform patterns % subplot(2,1,1),stem(H1); % % H2=LBP(I); % subplot(2,1,2),stem(H2); % % SP=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1]; % I2=LBP(I,SP,0,'i'); %LBP code image using sampling points in SP % %and no mapping. Now H2 is equal to histogram % %of I2. function result = lbp(varargin) % image,radius,neighbors,mapping,mode) % Version 0.3.2 % Authors: Marko Heikkila and Timo Ahonen % Changelog % Version 0.3.2: A bug fix to enable using mappings together with a % predefined spoints array % Version 0.3.1: Changed MAPPING input to be a struct containing the mapping % table and the number of bins to make the function run faster with high number % of sampling points. Lauge Sorensen is acknowledged for spotting this problem. % Check number of input arguments. error(nargchk(1,5,nargin)); image=varargin{1}; d_image=double(image); if nargin==1 spoints=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1]; neighbors=8; mapping=0; mode='h'; end if (nargin == 2) && (length(varargin{2}) == 1) error('Input arguments'); end if (nargin > 2) && (length(varargin{2}) == 1) radius=varargin{2}; neighbors=varargin{3}; spoints=zeros(neighbors,2); % Angle step. a = 2*pi/neighbors; for i = 1:neighbors spoints(i,1) = -radius*sin((i-1)*a); spoints(i,2) = radius*cos((i-1)*a); end if(nargin >= 4) mapping=varargin{4}; if(isstruct(mapping) && mapping.samples ~= neighbors) error('Incompatible mapping'); end else mapping=0; end if(nargin >= 5) mode=varargin{5}; else mode='h'; end end if (nargin > 1) && (length(varargin{2}) > 1) spoints=varargin{2}; neighbors=size(spoints,1); if(nargin >= 3) mapping=varargin{3}; if(isstruct(mapping) && mapping.samples ~= neighbors) error('Incompatible mapping'); end else mapping=0; end if(nargin >= 4) mode=varargin{4}; else mode='h'; end end % Determine the dimensions of the input image. [ysize xsize] = size(image); miny=min(spoints(:,1)); maxy=max(spoints(:,1)); minx=min(spoints(:,2)); maxx=max(spoints(:,2)); % Block size, each LBP code is computed within a block of size bsizey*bsizex bsizey=ceil(max(maxy,0))-floor(min(miny,0))+1; bsizex=ceil(max(maxx,0))-floor(min(minx,0))+1; % Coordinates of origin (0,0) in the block origy=1-floor(min(miny,0)); origx=1-floor(min(minx,0)); % Minimum allowed size for the input image depends % on the radius of the used LBP operator. if(xsize < bsizex || ysize < bsizey) error('Too small input image. Should be at least (2*radius+1) x (2*radius+1)'); end % Calculate dx and dy; dx = xsize - bsizex; dy = ysize - bsizey; % Fill the center pixel matrix C. C = image(origy:origy+dy,origx:origx+dx); d_C = double(C); bins = 2^neighbors; % Initialize the result matrix with zeros. result=zeros(dy+1,dx+1); %Compute the LBP code image for i = 1:neighbors y = spoints(i,1)+origy; x = spoints(i,2)+origx; % Calculate floors, ceils and rounds for the x and y. fy = floor(y); cy = ceil(y); ry = round(y); fx = floor(x); cx = ceil(x); rx = round(x); % Check if interpolation is needed. if (abs(x - rx) < 1e-6) && (abs(y - ry) < 1e-6) % Interpolation is not needed, use original datatypes N = image(ry:ry+dy,rx:rx+dx); D = N >= C; else % Interpolation needed, use double type images ty = y - fy; tx = x - fx; % Calculate the interpolation weights. w1 = (1 - tx) * (1 - ty); w2 = tx * (1 - ty); w3 = (1 - tx) * ty ; w4 = tx * ty ; % Compute interpolated pixel values N = w1*d_image(fy:fy+dy,fx:fx+dx) + w2*d_image(fy:fy+dy,cx:cx+dx) + ... w3*d_image(cy:cy+dy,fx:fx+dx) + w4*d_image(cy:cy+dy,cx:cx+dx); D = N >= d_C; end % Update the result matrix. v = 2^(i-1); result = result + v*D; end %Apply mapping if it is defined if isstruct(mapping) bins = mapping.num; for i = 1:size(result,1) for j = 1:size(result,2) result(i,j) = mapping.table(result(i,j)+1); end end end if (strcmp(mode,'h') || strcmp(mode,'hist') || strcmp(mode,'nh')) % Return with LBP histogram if mode equals 'hist'. result=hist(result(:),0:(bins-1)); if (strcmp(mode,'nh')) result=result/sum(result); end else %Otherwise return a matrix of unsigned integers if ((bins-1)<=intmax('uint8')) result=uint8(result); elseif ((bins-1)<=intmax('uint16')) result=uint16(result); else result=uint32(result); end end end % Mapping for sLBB function mapping = getsmapping(N,sk) M = 2^N; samples = N; len = zeros(M,1); ang = zeros(M,1); for x=0:(M-1) k = x+1; j = bitset(bitshift(x,1,samples),1,bitget(x,samples)); numt = sum(bitget(bitxor(x,j),1:samples)); c = numt; if c>2 len(k)=-1; ang(k)=-1; else s = bitget(x,1:samples); len(k) = sum(s); if c==0 ang(k)=0; else r = 0; while (s(1)~=0) || (s(N)~=1) s = [s(2:N) s(1)]; r = r+1; end ii = find(s==1); a = mean(ii)+r; if a>N a=a-N; end ang(k) = round(sk*a)-1; end end % fprintf('%4d: %s (%d,%d)\n',x,dec2bin(x,N),len(k),ang(k)); pause end Ma = max(ang)+1; map = len*Ma+ang-Ma+1; n = max(map)+1; map(ang==-1) = n; map(1) = 0; mapping.table = map'; mapping.samples = N; mapping.num = n+1; end
github
domingomery/Balu-master
Bfx_basicgeo.m
.m
Balu-master/FeatureExtraction/Bfx_basicgeo.m
2,763
utf_8
864db878ee7275da588d80683c9c45a7
% [X,Xn] = Bfx_geobasic(R,options) % % Toolbox: Balu % % Standard geometric features of a binary image R. This function calls % regionprops of Image Processing Toolbox. % % options.show = 1 display mesagges. % % X is the feature vector % Xn is the list of feature names. % % See expamle: % % Example: % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % [X,Xn] = Bfx_basicgeo(R); % basic geometric features % Bio_printfeatures(X,Xn) % % See also Bfx_fitellipse, Bfx_hugeo, Bfx_gupta, Bfx_flusser. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_basicgeo(R,options) if ~exist('options','var') options.show = 0; end N = size(R,1); warning off stats = regionprops(uint8(R),'EulerNumber','ConvexArea','EquivDiameter','Solidity','MajorAxisLength','Extent','MinorAxisLength','Orientation','FilledArea','Eccentricity'); warning on E = bwperim(R,4); % center of gravity [Ireg,Jreg] = find(R==1); % pixels in the region Kreg = Ireg+Jreg*N-N; % pixels of region stored in a vector i_m = mean(Ireg); % center of gravity in i direction j_m = mean(Jreg); % center of gravity in i direction % standard features % Perimeter if options.show == 1 disp('--- extracting standard geometric features...'); end L8 = sum(sum(bwperim(R,8))); L4 = sum(sum(bwperim(R,4))); L = (3*L4+L8)/4; % Area A = bwarea(R); % Roundness Roundness = 4*A*pi/L^2; % heigh & width i_max = max(Ireg); i_min = min(Ireg); j_max = max(Jreg); j_min = min(Jreg); height = i_max-i_min+1; % height width = j_max-j_min+1; % width % Danielsson shape factor (see Danielsson, 1977) TD = double(bwdist(not(R),'chessboard')); dm = mean(TD(Kreg)); Gd = A/9/pi/dm^2; X = [ i_m j_m height width A L Roundness Gd stats.EulerNumber stats.EquivDiameter stats.MajorAxisLength stats.MinorAxisLength stats.Orientation stats.Solidity stats.Extent stats.Eccentricity stats.ConvexArea stats.FilledArea]'; Xn = [ 'center of grav i [px] ' 'center of grav j [px] ' 'Height [px] ' 'Width [px] ' 'Area [px] ' 'Perimeter [px] ' 'Roundness ' 'Danielsson factor ' 'Euler Number ' 'Equivalent Diameter [px]' 'MajorAxisLength [px] ' 'MinorAxisLength [px] ' 'Orientation [grad] ' 'Solidity ' 'Extent ' 'Eccentricity ' 'Convex Area [px] ' 'Filled Area [px] '];
github
domingomery/Balu-master
Bfx_build.m
.m
Balu-master/FeatureExtraction/Bfx_build.m
9,784
utf_8
b85a3456e0fcefa8ff8f3e6e8fa60df0
% bf = Bfx_build({'all'}) % bf = Bfx_build({'allgeo'}) % bf = Bfx_build({'allint'}) % bf = Bfx_build({'haralick','lbp'}) % % Toolbox: Balu % Build structure for feature extraction with default values % % Posible geometric names: % 'basicgeo', % 'fitellipse', % 'fourierdes', % 'hugeo', % 'flusser', % 'gupta', % % Posible intenisty names: % 'basicint', % 'contrast', % 'haralick', % 'lbp', % 'lbps', % 'dct', % 'fourier', % 'gabor', % 'huint' % % Posible family names: % 'all' % 'allgeo' % 'allint' % % Example: % options.b = Bfx_build({'haralick','lbp'}); % options.colstr = 'rgb'; % R image % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % [X,Xn] = Bfx_int(I,R,options); % intensity features % Bio_printfeatures(X,Xn) % % See also Bcl_build, Bcl_balu. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl function bfx = Bfx_build(varargin) v = varargin; n = nargin; if compare(class(v),'cell')==0 v = v{1}; n = length(v); end if n==1 if compare(char(v(1)),'all')==0 v = {'basicgeo','fitellipse','fourierdes','hugeo','flusser','gupta','basicint','contrast','haralick','lbp','lbps','dct','fourier','gabor','huint'}; end if compare(char(v(1)),'allgeo')==0 v = {'basicgeo','fitellipse','fourierdes','hugeo','flusser','gupta'}; end if compare(char(v(1)),'allint')==0 v = {'basicint','contrast','haralick','lbp','lbps','dct','fourier','gabor','huint'}; end end n = length(v); if n==0 bfx = []; else for k=1:n s = char(v(k)); bfx(k).name = s; switch lower(s) % GEOMETRIC FEATURE EXTRACTION DEFINTION case 'basicgeo'; % basic geometric features bfx(k).options.type = 1; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'fitellipse'; % elliptic features bfx(k).options.type = 1; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'fourierdes'; % Fourier descriptors bfx(k).options.Nfourierdes = 16; % number of descriptors bfx(k).options.type = 1; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'hugeo'; % Hu moments bfx(k).options.type = 1; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'flusser'; % Flusser moments bfx(k).options.type = 1; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'gupta'; % Gupta moments bfx(k).options.type = 1; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results % INTENSITY FEATURE EXTRACTION DEFINTION case 'basicint'; % basic intensity features bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'contrast'; % contrast features bfx(k).options.neighbor = 2; % neigborhood is imdilate bfx(k).options.param = 5; % with 5x5 mask bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'clp'; % crossing line profile (CLP) bfx(k).options.ng = 32; % mask bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'haralick'; % statistical texture features bfx(k).options.dharalick = 1:5; % for 1, 2, ... 5 pixels bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'lbp'; % local binary batterns (LBP) bfx(k).options.vdiv = 1; % one vertical divition bfx(k).options.hdiv = 1; % one horizontal divition bfx(k).options.samples = 8; % number of neighbor samples bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'lbpri'; % local binary batterns (LBP) bfx(k).name = 'lbp'; bfx(k).options.vdiv = 1; % one vertical divition bfx(k).options.hdiv = 1; % one horizontal divition bfx(k).options.samples = 8; % number of neighbor samples bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results bfx(k).options.mappingtype = 'ri'; % rotation invariant case 'lbps'; % semantic LBP bfx(k).name = 'lbp'; bfx(k).options.vdiv = 1; % one vertical divition bfx(k).options.hdiv = 1; % one horizontal divition bfx(k).options.semantic = 1; % semantic LBP bfx(k).options.samples = 8; % number of neighbor samples bfx(k).options.sk = 0.5; % angle sampling bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'lbpw'; % weighted semantic LBP bfx(k).name = 'lbp'; bfx(k).options.vdiv = 1; % one vertical divition bfx(k).options.hdiv = 1; % one horizontal divition bfx(k).options.semantic = 0; % semantic LBP bfx(k).options.weight = 9; % semantic LBP bfx(k).options.samples = 8; % number of neighbor samples bfx(k).options.sk = 0.5; % angle sampling bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case {'lbpws','lbpsw'}; % weighted & semantic LBP bfx(k).name = 'lbp'; bfx(k).options.vdiv = 1; % one vertical divition bfx(k).options.hdiv = 1; % one horizontal divition bfx(k).options.semantic = 1; % semantic LBP bfx(k).options.weight = 9; % semantic LBP bfx(k).options.samples = 8; % number of neighbor samples bfx(k).options.sk = 0.5; % angle sampling bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'dct'; % Discrete Cosinus Transform bfx(k).options.Ndct = 64; % imresize vertical bfx(k).options.Mdct = 64; % imresize horizontal bfx(k).options.mdct = 4; % imresize frequency vertical bfx(k).options.ndct = 4; % imresize frequency horizontal bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'fourier'; % Discrete Fourier Transform bfx(k).options.Nfourier = 64; % imresize vertical bfx(k).options.Mfourier = 64; % imresize horizontal bfx(k).options.mfourier = 4; % imresize frequency vertical bfx(k).options.nfourier = 4; % imresize frequency horizontal bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'gabor'; % Gabor features bfx(k).options.Lgabor = 8; % number of rotations bfx(k).options.Sgabor = 8; % number of dilations (scale) bfx(k).options.fhgabor = 2; % highest frequency of interest bfx(k).options.flgabor = 0.1; % lowest frequency of interest bfx(k).options.Mgabor = 21; % mask size bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results case 'huint'; % Hu-moments with intensity bfx(k).options.type = 2; % 1 geometric 2 intensity bfx(k).options.show = 1; % display results otherwise error('Bfx_build does not recognize %s as feature extraction method.',s) end end end
github
domingomery/Balu-master
Bfx_gupta.m
.m
Balu-master/FeatureExtraction/Bfx_gupta.m
1,702
utf_8
9f533fbbc4a7c7b467d14e83acc0aa8c
% [X,Xn] = Bfx_gupta(R,options) % % Toolbox: Balu % % Extract the three Gupta moments from binary image R. % % options.show = 1 display mesagges. % % X is a 3 elements vector: % X(i): Gupta-moment i for i=1,2,3. % Xn is the list of feature names. % % Reference: % Gupta, L. & Srinath, M. D. Contour sequence moments for the % classification of closed planar shapes Pattern Recognition, 1987, 20, % 267-272. % % Example: % I = imread('testimg3.jpg'); % input image % R = Bim_segbalu(I); % segmentation % [L,n] = bwlabel(R); % regions % imshow(L,[]) % X = []; % for i=1:n % [Xi,Xn] = Bfx_gupta(L==i); % Gupta moments % X = [X;Xi]; % end % X % % See also Bfx_basicgeo, Bfx_hugeo, Bfx_fitellipse, Bfx_flusser. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_gupta(R,options) if ~exist('options','var') options.show = 0; end if options.show == 1 disp('--- extracting Gupta moments...'); end E = bwperim(R,4); [Ip,Jp] = find(E==1); % pixel of perimeter in (i,j) jj = sqrt(-1); Ig = Ip+jj*Jp; ix = mean(Ip); jx = mean(Jp); centre = ix + jj*jx; z = abs(Ig-centre); m1 = mean(z); mur1 = z-m1; mur2 = mur1.*mur1; mur3 = mur1.*mur2; mur4 = mur2.*mur2; mu2 = mean(mur2); mu3 = mean(mur3); mu4 = mean(mur4); F1 = sqrt(mu2)/m1; F2 = mu3/mu2/sqrt(mu2); F3 = mu4/mu2^2; X = [F1 F2 F3]; Xn = [ 'Gupta-moment 1 ' 'Gupta-moment 2 ' 'Gupta-moment 3 '];
github
domingomery/Balu-master
Bfx_clp.m
.m
Balu-master/FeatureExtraction/Bfx_clp.m
4,246
utf_8
6693b6f561692d32557a46eb19e87152
% [X,Xn] = Bfx_clp(I,R,options) % [X,Xn] = Bfx_clp(I,options) % % Toolbox Balu: Crossing Line Profile. % % X is the features vector, Xn is the list of feature names(see Example % to see how it works). % % Reference: % Mery, D.: Crossing line profile: a new approach to detecting defects % in aluminium castings. Proceedings of the Scandinavian Conference on % Image Analysis 2003 (SCIA 2003), Lecture Notes in Computer Science % LNCS 2749: 725-732, 2003. % % Example: % options.show = 1; % display results % options.ng = 32; % windows resize % I = imread('testimg4.jpg'); % input image % J = I(395:425,415:442,1); % region of interest (red) % R = J>135; % segmentation % figure;imshow(J,[]) % figure;imshow(R) % [X,Xn] = Bfx_clp(J,R,options); % CLP features % Bio_printfeatures(X,Xn) % % See also Xcontrast, Xharalick, Bfx_clp, Xfourier, Xdct, Xlbp. % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_clp(I,R,options) [N,M] = size(I); I = double(I); if nargin==2; options = R; R = ones(N,M); end if ~isfield(options,'show') options.show = 0; end if options.show == 1 disp('--- extracting Crossing line profile features...'); end show = options.show; [ii,jj] = find(R==1); h = max(ii)-min(ii)+1; % height w = max(jj)-min(jj)+1; % width x = round(Xcentroid(R)); % mass center i1 = max([1 x(1)-h]); j1 = max([1 x(2)-w]); i2 = min([N x(1)+h]); j2 = min([M x(2)+w]); %if ~isempty(R); % I(R==0) = 0; %end ng = options.ng; Bn = imresize(I(i1:i2,j1:j2),[ng ng]); mg = fix(ng/2+1); % Crossing line profiles P0 = Bn(mg,:)'; % 0.0 ... 90.0 4 P1 = Bn(:,mg); % 90.0 ... 0.0 0 P2 = zeros(ng,1); % 45.0 ... 135.0 6 P3 = zeros(ng,1); % 135.0 ... 45.0 2 P4 = zeros(ng,1); % 22.5 ... 112.5 5 P5 = zeros(ng,1); % 67.5 ... 157.5 7 P6 = zeros(ng,1); % 112.5 ... 22.5 1 P7 = zeros(ng,1); % 157.5 ... 67.5 3 Q0 = Bn; Q1 = Bn; Q2 = Bn; Q3 = Bn; Q4 = Bn; Q5 = Bn; Q6 = Bn; Q7 = Bn; Q0(mg,:) = 255*ones(1,ng); Q1(:,mg) = 255*ones(ng,1); m4 = mg/(ng-1); b4 = mg/2-m4; b7 = 3*mg/2+mg/(ng-1); for i=1:ng P2(i,1) = Bn(i,i); Q2(i,i) = 255; P3(i,1) = Bn(i,ng-i+1); Q3(i,ng-i+1) = 255; j4 = fix(m4*i + b4 + 0.5); P4(i,1) = Bn(j4,i); Q4(j4,i) = 255; P5(i,1) = Bn(i,j4); Q5(i,j4) = 255; j7 = fix(-m4*i + b7 + 0.5); P6(i,1) = Bn(i,j7); Q6(i,j7) = 255; P7(i,1) = Bn(j7,i); Q7(j7,i) = 255; end PP = [P0 P1 P2 P3 P4 P5 P6 P7]; d = abs(PP(1,:)-PP(ng,:)); [~,J] = sort(d); Po = PP(:,J(1)); Po = Po/Po(1); m = (Po(ng)-Po(1))/(ng - 1); mb = Po(1)-m; Q = Po-(1:ng)'*m-ones(ng,1)*mb; Qm = mean(Q); Qd = max(Q)-min(Q); Qd1 = log(Qd+1); Qd2 = 2*Qd/(Po(1)+Po(ng)); Qs = std(Q); Qf = fft(Q); Qf = abs(Qf(2:8,1)); if (show) figure(10) clf subplot(2,4,5);plot(PP(:,1));axis([1 ng 0 255]);title('k=4'); subplot(2,4,1);plot(PP(:,2));axis([1 ng 0 255]);title('k=0'); subplot(2,4,3);plot(PP(:,3));axis([1 ng 0 255]);title('k=2'); subplot(2,4,7);plot(PP(:,4));axis([1 ng 0 255]);title('k=6'); subplot(2,4,4);plot(PP(:,5));axis([1 ng 0 255]);title('k=3'); subplot(2,4,2);plot(PP(:,6));axis([1 ng 0 255]);title('k=1'); subplot(2,4,8);plot(PP(:,7));axis([1 ng 0 255]);title('k=7'); subplot(2,4,6);plot(PP(:,8));axis([1 ng 0 255]);title('k=5'); figure(11) imshow([Q1 Q5 Q2 Q4;Q0 Q7 Q3 Q6],gray(256)); pause(0); end X = [Qm Qs Qd Qd1 Qd2 Qf']; Xn = [ 'CLP-Qm ' 'CLP-Qs ' 'CLP-Qd ' 'CLP-Qd1 ' 'CLP-Qd2 ' 'CLP-Qf1 ' 'CLP-Qf2 ' 'CLP-Qf3 ' 'CLP-Qf4 ' 'CLP-Qf5 ' 'CLP-Qf6 ' 'CLP-Qf7 '];
github
domingomery/Balu-master
Bfx_gabor.m
.m
Balu-master/FeatureExtraction/Bfx_gabor.m
3,540
utf_8
36d1e30d3fea9e840ac1b5566302615e
% [X,Xn] = Bfx_gabor(I,R,options) % [X,Xn] = Bfx_gabor(I,options) % % Toolbox: Balu % Gabor features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % Reference: % Kumar, A.; Pang, G.K.H. (2002): Defect detection in textured materials % using Gabor filters. IEEE Transactions on Industry Applications, % 38(2):425-440. % % Example: % options.Lgabor = 8; % number of rotations % options.Sgabor = 8; % number of dilations (scale) % options.fhgabor = 2; % highest frequency of interest % options.flgabor = 0.1; % lowest frequency of interest % options.Mgabor = 21; % mask size % options.show = 1; % display results % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % J = I(:,:,2); % green channel % [X,Xn] = Bfx_gabor(J,R,options); % Gabor features % Bio_printfeatures(X,Xn) % % See also Bfx_haralick, Bfx_clp, Bfx_fourier, Bfx_dct, Bfx_lbp. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_gabor(I,R,options) if nargin==2; options = R; R = ones(size(I)); end L = options.Lgabor; S = options.Sgabor; fh = options.fhgabor; fl = options.flgabor; M = options.Mgabor; if options.show disp('--- extracting Gabor features...'); end alpha = (fh/fl)^(1/(S-1)); sx = sqrt(2*log(2))*(alpha+1)/2/pi/fh/(alpha-1); sy = sqrt(2*log(2)-(2*log(2)/2/pi/sx/fh)^2)/(2*pi*tan(pi/2/L)*(fh-2*log(1/4/pi^2/sx^2/fh))); u0 = fh; k = R==1; g = zeros(S,L); size_out = size(I)+[M M]-1; Iw = fft2(I,size_out(1),size_out(2)); n1 = (M+1)/2; [NN,MM] = size(I); for p=1:S; for q=1:L f = Bgabor_pq(p,q,L,sx,sy,u0,alpha,M); %This convolution is very slow: %Ir = conv2(I,real(f),'same'); %Ii = conv2(I,imag(f),'same'); %Iout = sqrt(Ir.*Ir + Ii.*Ii); Ir = real(ifft2(Iw.*fft2(real(f),size_out(1),size_out(2)))); Ii = real(ifft2(Iw.*fft2(imag(f),size_out(1),size_out(2)))); Ir = Ir(n1:n1+NN-1,n1:n1+MM-1); Ii = Ii(n1:n1+NN-1,n1:n1+MM-1); Iout = sqrt(Ir.*Ir + Ii.*Ii); g(p,q) = mean(Iout(k)); end; end gmax = max(g(:)); gmin = min(g(:)); J = (gmax-gmin)/gmin; X = [g(:); gmax; gmin; J]'; LS = L*S; Xn = char(zeros(LS+3,24)); k = 0; for p=1:S; for q=1:L k = k + 1; Xn(k,:) = sprintf('Gabor(%d,%d) ',p,q); end end Xn(LS+1,:) = 'Gabor-max '; Xn(LS+2,:) = 'Gabor-min '; Xn(LS+3,:) = 'Gabor-J '; % f = Bgabor_pq(p,q,L,S,sx,sy,u0,alpha,M) % % Toolbox: Balu % Gabor kernel. See details in: % Kumar, A.; Pang, G.K.H. (2002): Defect detection in textured materials % using Gabor filters. IEEE Transactions on Industry Applications, % 38(2):425-440. % % D.Mery, PUC-DCC, Apr. 2008 % http://dmery.ing.puc.cl % function f = Bgabor_pq(p,q,L,sx,sy,u0,alpha,M) f = zeros(M,M); sx2 = sx*sx; sy2 = sy*sy; c = (M+1)/2; ap = alpha^-p; tq = pi*(q-1)/L; f_exp = 2*pi*sqrt(-1)*u0; for i=1:M x = i - c; for j=1:M y = j - c; x1 = ap*(x*cos(tq)+y*sin(tq)); y1 = ap*(y*cos(tq)-x*sin(tq)); f(i,j) = exp(-0.5*(x1*x1/sx2+y1*y1/sy2))*exp(f_exp*x1); end end f = ap*f/2/pi/sx/sy;
github
domingomery/Balu-master
Bfx_lbphogi.m
.m
Balu-master/FeatureExtraction/Bfx_lbphogi.m
1,285
utf_8
697f23969b6f2ca4fe58208a9d934672
% [X,Xn] = Bfx_hog(I,options) % % Toolbox: Balu % Histogram of Orientated Gradients features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % options.nj; : number of HOG windows per bound box % options.ni : in i (vertical) and j (horizaontal) direction % options.B : number of histogram bins % options.show : show histograms (glyphs) % % Example: % options.nj = 20; % 10 x 20 % options.ni = 10; % histograms % options.B = 9; % 9 bins % options.show = 1; % number of neighbor samples % I = imread('testimg1.jpg'); % input image % J = rgb2gray(I); % figure(1);imshow(J,[]); % figure(2); % [X,Xn] = Bfx_hog(J,options); % HOG features (see gradients % % arround perimeter. % % See also Bfx_phog, Bfx_lbp. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % function [X,Xn,options] = Bfx_lbphogi(I,R,options) if nargin==2; options = R; R = []; end [X_lbp,Xn_lbp] = Bfx_lbpi(I,R,options); [X_hog,Xn_hog] = Bfx_hogi(I,R,options); X = [X_lbp X_hog ]; Xn = [Xn_lbp; Xn_hog];
github
domingomery/Balu-master
Bfx_gui.m
.m
Balu-master/FeatureExtraction/Bfx_gui.m
47,257
utf_8
55d8165e26f39e53841b072ed7bd1721
% Bfx_gui % % Toolbox: Balu % % Graphic User Interface for feature extraction. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl function varargout = Bfx_gui(varargin) % BFX_GUI M-file for Bfx_gui.fig % BFX_GUI, by itself, creates a new BFX_GUI or raises the existing % singleton*. % % H = BFX_GUI returns the handle to a new BFX_GUI or the handle to % the existing singleton*. % % BFX_GUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in BFX_GUI.M with the given input arguments. % % BFX_GUI('Property','Value',...) creates a new BFX_GUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before Bfx_gui_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to Bfx_gui_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help Bfx_gui % Last Modified by GUIDE v2.5 17-Nov-2011 10:21:48 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Bfx_gui_OpeningFcn, ... 'gui_OutputFcn', @Bfx_gui_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before Bfx_gui is made visible. function Bfx_gui_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to Bfx_gui (see VARARGIN) % Choose default command line output for Bfx_gui handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes Bfx_gui wait for user response (see UIRESUME) % uiwait(handles.figure1); clc disp('Balu 3.0: GUI for Feature Extraction.') disp(' ') disp('This GUI will extract features from current directory:') cd disp('Warning: not all features implemented in Balu are in this GUI.'); disp(' ') disp('Please define the feature extraction process in the GUI window,'); disp('and press [Go] when you finish.') disp(' ') global Img Imgnow fextractor Nimg sfiles pseg mseg seg fsname fextractor.formatimg = 1; fextractor.resizeimg = 1; fextractor.geostandard = 0; fextractor.geoinvariant = 0; fextractor.geofourierdes = 0; fextractor.geoelliptical = 0; fextractor.intstandard = 0; fextractor.intcontrast = 0; fextractor.intharalick = 0; fextractor.intfourierdct = 0; fextractor.inthuint = 0; fextractor.intgabor = 0; fextractor.intlbp = 0; fextractor.inthog = 0; fextractor.colorgray = 0; fextractor.colorred = 0; fextractor.colorgreen = 0; fextractor.colorblue = 0; fextractor.colorhue = 0; fextractor.colorsat = 0; fextractor.colorval = 0; fextractor.colorl = 0; %%%% Conversion RGB -> L*a*b* fextractor.colora = 0; % 0 = no, 1 = calibrated (Bim_rgb2lab), fextractor.colorb = 0; % 2 = formulas (Bim_rgb2lab0) fextractor.segmentation = 0; fextractor.partition = 1; fextractor.outmatlab = 0; fextractor.outascii = 0; fextractor.outexcel = 0; axis off pseg = -0.05; mseg = 0; Nimg = 1; seg = 0; fsname = 0; sfiles = dir('*.jpg'); if not(isempty(sfiles)) % error('Balu Error: Current directory does not contain any image') %else Img = imread(sfiles(Nimg).name); Imgnow = Img; subplot(1,1,1); imshow(Img) title(sfiles(Nimg).name) end % --- Outputs from this function are returned to the command line. function varargout = Bfx_gui_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in ButtonGo. function ButtonGo_Callback(hObject, eventdata, handles) % hObject handle to ButtonGo (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global fextractor ok = 1; fgeo = fextractor.geostandard+fextractor.geoinvariant+... fextractor.geofourierdes+fextractor.geoelliptical; fint = fextractor.intstandard+fextractor.intcontrast+... fextractor.intharalick+fextractor.intfourierdct+... fextractor.inthuint+fextractor.intgabor+fextractor.intlbp+... fextractor.inthog; fcol = fextractor.colorgray+fextractor.colorred+fextractor.colorgreen+... fextractor.colorblue+fextractor.colorhue+fextractor.colorsat+... fextractor.colorval+fextractor.colorl+fextractor.colora+... fextractor.colorb; fout = fextractor.outmatlab+fextractor.outascii+fextractor.outexcel; if fgeo+fint==0 beep wwarndlg('You must set some features.','Error in Bfx_gui'); ok = 0; end if and(fint>0,fcol==0) beep wwarndlg('If you select color features, you must set color component(s).','Error in Bfx_gui'); ok = 0; end if and(fint==0,fcol>0) beep wwarndlg('If you select color component(s), you must set color features.','Error in Bfx_gui'); ok = 0; end if (fout==0) beep wwarndlg('You must set output file format (Matlab, Text or Excel).','Error in Bfx_gui'); ok = 0; end if ok yesnoans = questdlg('Bfx_gui will start to extract all features. This process could take several minutes. Are you sure?', ... 'Bfx_gui Information', ... 'Yes', 'No', 'No'); if yesnoans(1)=='Y' save Bfx_guidata fextractor [f,fn] = Bfx_guifun(fextractor); questdlg(sprintf('Bfx_gui ended successfully: %d features extracted from %d images.',size(f,2),size(f,1)),'Bfx_gui Information','Ok', 'Ok'); end end % --- Executes on button press in Gray. function Gray_Callback(hObject, eventdata, handles) % hObject handle to Gray (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Gray global Imgnow fextractor val = get(hObject,'Value'); if val if size(Imgnow,3)==1 subplot(1,1,1); imshow(Imgnow) else subplot(1,1,1); imshow(rgb2gray(Imgnow)) end else subplot(1,1,1); imshow(Imgnow); end fextractor.colorgray = val; % --- Executes on button press in Red. function Red_Callback(hObject, eventdata, handles) % hObject handle to Red (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Red global Imgnow fextractor val = get(hObject,'Value'); if val subplot(1,1,1); imshow(uint8(Imgnow(:,:,1)),[(1:256)'/256 zeros(256,2)]) else subplot(1,1,1); imshow(Imgnow); end fextractor.colorred = val; % --- Executes on button press in Green. function Green_Callback(hObject, eventdata, handles) % hObject handle to Green (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Green global Imgnow fextractor val = get(hObject,'Value'); if val subplot(1,1,1); imshow(uint8(Imgnow(:,:,2)),[zeros(256,1) (1:256)'/256 zeros(256,1)]) else subplot(1,1,1); imshow(Imgnow); end fextractor.colorgreen = val; % --- Executes on button press in Blue. function Blue_Callback(hObject, eventdata, handles) % hObject handle to Blue (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Blue global Imgnow fextractor val = get(hObject,'Value'); if val subplot(1,1,1); imshow(uint8(Imgnow(:,:,3)),[zeros(256,2) (1:256)'/256]) else subplot(1,1,1); imshow(Imgnow); end fextractor.colorblue = val; % --- Executes on button press in Hue. function Hue_Callback(hObject, eventdata, handles) % hObject handle to Hue (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Hue global Imgnow fextractor val = get(hObject,'Value'); if val H = rgb2hsv(Imgnow); H(:,:,2) = 1; H(:,:,3) = 1; subplot(1,1,1); imshow(hsv2rgb(H)) else subplot(1,1,1); imshow(Imgnow); end fextractor.colorhue = val; % --- Executes on button press in Sat. function Sat_Callback(hObject, eventdata, handles) % hObject handle to Sat (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Sat global Imgnow fextractor val = get(hObject,'Value'); if val H = rgb2hsv(Imgnow); subplot(1,1,1); imshow(H(:,:,2)) else subplot(1,1,1); imshow(Imgnow); end fextractor.colorsat = val; % --- Executes on button press in Val. function Val_Callback(hObject, eventdata, handles) % hObject handle to Val (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Val global Imgnow fextractor val = get(hObject,'Value'); if val H = rgb2hsv(Imgnow); subplot(1,1,1); imshow(H(:,:,3)) else subplot(1,1,1); imshow(Imgnow); end fextractor.colorval = val; % --- Executes on button press in L. function L_Callback(hObject, eventdata, handles) % hObject handle to L (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of L global Imgnow fextractor val = get(hObject,'Value'); if val if (exist('LAB.mat','file')) load LAB L = Bim_rgb2lab(Imgnow,M); subplot(1,1,1); imshow(L(:,:,1),[]) else beep yesnoans = questdlg('Calibrated LAB conversion cannot be possible because LAB.mat file does not exist. Do you want to convert RGB to L*a*b* using CIE formulas?', ... 'Bfx_gui RGB -> L*a*b conversion', ... 'Yes', 'No', 'No'); if yesnoans(1)=='Y' val = 2; L = Bim_rgb2lab0(Imgnow); subplot(1,1,1); imshow(L(:,:,1),[]) else wwarndlg('L*a*b* conversion is not possible, because LAB.mat file does not exist.','Error in Bfx_gui'); set(hObject,'Value',0); val = 0; end end else subplot(1,1,1); imshow(Imgnow); end fextractor.colorl = val; % --- Executes on button press in a. function a_Callback(hObject, eventdata, handles) % hObject handle to a (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of a global Imgnow fextractor val = get(hObject,'Value'); if val if (exist('LAB.mat','file')) load LAB L = rgb2lab(Imgnow,M); subplot(1,1,1); imshow(L(:,:,2),[]) else beep yesnoans = questdlg('Calibrated LAB conversion cannot be possible because LAB.mat file does not exist. Do you want to convert RGB to L*a*b* using CIE formulas?', ... 'Bfx_gui RGB -> L*a*b conversion', ... 'Yes', 'No', 'No'); if yesnoans(1)=='Y' val = 2; L = Bim_rgb2lab0(Imgnow); subplot(1,1,1); imshow(L(:,:,2),[]) else wwarndlg('L*a*b* conversion is not possible, because LAB.mat file does not exist.','Error in Bfx_gui'); set(hObject,'Value',0); val = 0; end end else subplot(1,1,1); imshow(Imgnow); end fextractor.colora = val; % --- Executes on button press in b. function b_Callback(hObject, eventdata, handles) % hObject handle to b (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of b global Imgnow fextractor val = get(hObject,'Value'); if val if (exist('LAB.mat','file')) load LAB L = rgb2lab(Imgnow,M); subplot(1,1,1); imshow(L(:,:,3),[]) else beep yesnoans = questdlg('Calibrated LAB conversion cannot be possible because LAB.mat file does not exist. Do you want to convert RGB to L*a*b* using CIE formulas?', ... 'Bfx_gui RGB -> L*a*b conversion', ... 'Yes', 'No', 'No'); if yesnoans(1)=='Y' val = 2; L = Bim_rgb2lab0(Imgnow); subplot(1,1,1); imshow(L(:,:,3),[]) else wwarndlg('L*a*b* conversion is not possible, because LAB.mat file does not exist.','Error in Bfx_gui'); set(hObject,'Value',0); val = 0; end end else subplot(1,1,1); imshow(Imgnow); end fextractor.colorb = val; % --- Executes on button press in Matlab. function Matlab_Callback(hObject, eventdata, handles) % hObject handle to Matlab (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Matlab global fextractor fextractor.outmatlab = get(hObject,'Value'); % --- Executes on button press in Ascii. function Ascii_Callback(hObject, eventdata, handles) % hObject handle to Ascii (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Ascii global fextractor fextractor.outascii = get(hObject,'Value'); % --- Executes on button press in Excel. function Excel_Callback(hObject, eventdata, handles) % hObject handle to Excel (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Excel global fextractor fextractor.outexcel = get(hObject,'Value'); % --- Executes on button press in GeoStandard. function GeoStandard_Callback(hObject, eventdata, handles) % hObject handle to GeoStandard (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of GeoStandard global fextractor fextractor.geostandard = get(hObject,'Value'); if (fextractor.segmentation == 0) && (fextractor.geostandard == 1) wwarndlg('Geometrical features with no segmentation? Bad idea :(','Warning in Bfx_gui'); end % --- Executes on button press in IntMoments. function IntMoments_Callback(hObject, eventdata, handles) % hObject handle to IntMoments (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of IntMoments global fextractor fextractor.geoinvariant = get(hObject,'Value'); if (fextractor.segmentation == 0) && (fextractor.geoinvariant == 1) wwarndlg('Geometrical features with no segmentation? Bad idea :(','Warning in Bfx_gui'); end % --- Executes on button press in FourierDesc. function FourierDesc_Callback(hObject, eventdata, handles) % hObject handle to FourierDesc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of FourierDesc global fextractor fextractor.geofourierdes = get(hObject,'Value'); if (fextractor.segmentation == 0) && (fextractor.geofourierdes == 1) wwarndlg('Geometrical features with no segmentation? Bad idea :(','Warning in Bfx_gui'); end % --- Executes on button press in Elliptical. function Elliptical_Callback(hObject, eventdata, handles) % hObject handle to Elliptical (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of Elliptical global fextractor fextractor.geoelliptical = get(hObject,'Value'); if (fextractor.segmentation == 0) && (fextractor.geoelliptical == 1) wwarndlg('Geometrical features with no segmentation? Bad idea :(','Warning in Bfx_gui'); end % --- Executes on button press in IntStandard. function IntStandard_Callback(hObject, eventdata, handles) % hObject handle to IntStandard (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of IntStandard global fextractor fextractor.intstandard = get(hObject,'Value'); % --- Executes on button press in IntContrast. function IntContrast_Callback(hObject, eventdata, handles) % hObject handle to IntContrast (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of IntContrast global fextractor fextractor.intcontrast = get(hObject,'Value'); % --- Executes on button press in IntHaralick. function IntHaralick_Callback(hObject, eventdata, handles) % hObject handle to IntHaralick (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of IntHaralick global fextractor fextractor.intharalick = get(hObject,'Value'); % --- Executes on button press in IntFourierDCT. function IntFourierDCT_Callback(hObject, eventdata, handles) % hObject handle to IntFourierDCT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of IntFourierDCT global fextractor fextractor.intfourierdct = get(hObject,'Value'); % --- Executes on button press in IntHu. function IntHu_Callback(hObject, eventdata, handles) % hObject handle to IntHu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of IntHu global fextractor fextractor.inthuint = get(hObject,'Value'); % --- Executes on button press in IntGabor. function IntGabor_Callback(hObject, eventdata, handles) % hObject handle to IntGabor (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of IntGabor global fextractor fextractor.intgabor = get(hObject,'Value'); % --- Executes on selection change in FormatImg. function FormatImg_Callback(hObject, eventdata, handles) % hObject handle to FormatImg (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns FormatImg contents as cell array % contents{get(hObject,'Value')} returns selected item from FormatImg global Img Imgnow fextractor Nimg sfiles fextractor.formatimg = get(hObject,'Value'); s = dir('*.jpg'); if not(isempty(s)) % error('Balu Error: Current directory does not contain any image') %else end switch fextractor.formatimg case 2 s = 'tif'; case 3 s = 'bmp'; case 4 s = 'png'; case 5 s = 'ppm'; case 6 s = 'gif'; case 7 s = 'pbm'; otherwise s = 'jpg'; end if isempty(s) beep wwarndlg('Current directory does not contain any image with this format.','Error in Bfx_gui'); else sfiles = [dir(['*.' lower(s)]); dir(['*.' upper(s)])]; Nimg = 1; Img = imread(sfiles(1).name); Imgnow = Img; subplot(1,1,1); imshow(Img) title(sfiles(Nimg).name) end % --- Executes during object creation, after setting all properties. function FormatImg_CreateFcn(hObject, eventdata, handles) % hObject handle to FormatImg (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ImgResize_Callback(hObject, eventdata, handles) % hObject handle to ImgResize (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ImgResize as text % str2double(get(hObject,'String')) returns contents of ImgResize as a double global fextractor Img Imgnow fextractor.resizeimg = str2num(get(hObject,'String')); warning off Imgnow = imresize(Img,fextractor.resizeimg); warning on subplot(1,1,1); imshow(Imgnow) % --- Executes during object creation, after setting all properties. function ImgResize_CreateFcn(hObject, eventdata, handles) % hObject handle to ImgResize (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in ImgSegmentation. function ImgSegmentation_Callback(hObject, eventdata, handles) % hObject handle to ImgSegmentation (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns ImgSegmentation contents as cell array % contents{get(hObject,'Value')} returns selected item from ImgSegmentation global fextractor Imgnow pseg seg mseg fsname fextractor.segmentation = get(hObject,'Value')-1; seg = fextractor.segmentation; fsname = 0; PlotImage(Imgnow,seg,pseg,mseg); function [R,E,J] = SegImage(Imgnow,seg,pseg,mseg) global fsname [N,M,P] = size(Imgnow); switch seg case 1 % balu [R,E,J] = Bim_segbalu(Imgnow,pseg); case 2 % maxvar [R,E,J] = Bim_segmaxvar(Imgnow,pseg); case 3 % maxfisher [R,E,J] = Bim_segmaxfisher(Imgnow,pseg); case 4 % otsu [R,E,J] = Bim_segotsu(Imgnow,pseg); case 5 [R,E,J] = Bim_segpca(Imgnow,pseg); case 6 if fsname == 0 sname = input('Input segmentation program name: '); fsname = ['[R,E,J] = ' sname '(Imgnow,pseg);']; end eval(fsname); otherwise R = ones(N,M); if (P==3) J = rgb2gray(Imgnow); else J = Imgnow; end R = ones(size(J)); E = zeros(size(J)); end if mseg R = bwlabel(R); end function PlotImage(Imgnow,seg,pseg,mseg) [R,E,J] = SegImage(Imgnow,seg,pseg,mseg); [N,M,P] = size(Imgnow); subplot(1,1,1); imshow(R,[]) pause(1) ii = find(R==0); if isempty('RR') Iw = Imgnow; else if (P==3) Ir = Imgnow(:,:,1);Ir(ii)=0; Ig = Imgnow(:,:,2);Ig(ii)=0; Ib = Imgnow(:,:,3);Ib(ii)=0; Iw = zeros(size(Imgnow)); Iw(:,:,1) = Ir; Iw(:,:,2) = Ig; Iw(:,:,3) = Ib; else Iw = Imgnow; Iw(ii) = 0; end subplot(1,1,1); imshow(uint8(Iw)) end % --- Executes during object creation, after setting all properties. function ImgSegmentation_CreateFcn(hObject, eventdata, handles) % hObject handle to ImgSegmentation (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in lbp. function lbp_Callback(hObject, eventdata, handles) % hObject handle to lbp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of lbp global fextractor fextractor.intlbp = get(hObject,'Value'); % --- Executes on selection change in Partition. function Partition_Callback(hObject, eventdata, handles) % hObject handle to Partition (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns Partition contents as cell array % contents{get(hObject,'Value')} returns selected item from Partition global fextractor Imgnow fextractor.partition = get(hObject,'Value'); [N,M,P] = size(Imgnow); n = N/fextractor.partition; m = M/fextractor.partition; subplot(1,1,1); imshow(Imgnow) hold on for i=0:n:N plot([1 M],[i i]) end for j=0:m:M plot([j j],[1 N]) end hold off % --- Executes during object creation, after setting all properties. function Partition_CreateFcn(hObject, eventdata, handles) % hObject handle to Partition (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % Bfx_guifun % % Toolbox: Balu % Extract feactures of all images of courrent directory and store. % The extracted features are stored in excel, text or matlab files. % A list of the names of the images is stored in imgnames.txt % f = table of features, fn = name of features % % fetractor is a structure with following variables: % % fextractor.formatimg 1=jpg|2=tif|3=bmp|4=png|5=ppm|6=png|7=pbm % fextractor.resizeimg 0=no|0.5, 0.25, [16 16], [32 32], [200 200] % fextractor.geostandard 1=yes|0=no % fextractor.geoinvariant : % fextractor.geofourierdes % fextractor.geoelliptical % fextractor.intstandard % fextractor.intcontrast : % fextractor.intharalick % fextractor.intfourierdct % fextractor.inthuint % fextractor.intgabor % fextractor.intlbp % fextractor.colorgray % fextractor.colorred : % fextractor.colorgreen % fextractor.colorblue % fextractor.colorhue % fextractor.colorsat % fextractor.colorval : % fextractor.colorl % fextractor.colora % fextractor.colorb % fextractor.segmentation 1=yes | 0 = no (whole image) % fextractor.outmatlab % fextractor.outascii % fextractor.outexcel % % D.Mery, PUC-DCC, Apr. 2008 % http://dmery.ing.puc.cl % function [f,fn]=Bfx_guifun(fextractor) fsb = Bio_statusbar('Extracting features'); global pseg mseg seg disp('Balu Full Features Extractor'); disp(' '); reset(gca); imgfmt = fextractor.formatimg; fg = zeros(10,1); fi = zeros(10,1); co = zeros(20,1); fg(1) = fextractor.geostandard; fg(2) = fextractor.geoinvariant; fg(3) = fextractor.geofourierdes; fg(4) = fextractor.geoelliptical; rg = sum(fg)>0; fi(1) = fextractor.intstandard; fi(2) = fextractor.intcontrast; fi(3) = fextractor.intharalick; fi(4) = fextractor.intfourierdct; fi(5) = fextractor.inthuint; fi(6) = fextractor.intgabor; fi(7) = fextractor.intlbp; fi(8) = fextractor.inthog; ri = sum(fi)>0; co(1) = fextractor.colorgray; co(2) = fextractor.colorred; co(3) = fextractor.colorgreen; co(4) = fextractor.colorblue; co(5) = fextractor.colorhue; co(6) = fextractor.colorsat; co(7) = fextractor.colorval; co(8) = fextractor.colorl; co(9) = fextractor.colora; co(10)= fextractor.colorb; if and(sum(co)>0,sum(fi)==0) disp('Warning: No intensity feature will be extracted, because no intensity feature was marked. ') ri = 0; end if and(sum(co)==0,sum(fi)>0) disp('Warning: No intensity feature will be extracted, because no color component was marked. ') ri = 0; end if (sum(co(8:10)>0)>0) rgblabconv = (sum(co(8:10)==2)>0)+1; else rgblabconv = 0; end if (sum([fg;fi])==0) error('No feature will be extracted, because there is no feature marked. ') end imgseg = fextractor.segmentation; imgpart = fextractor.partition; if imgpart == 0 imgpart = 1; % no partition means one partition! end oxls = fextractor.outexcel; otxt = fextractor.outascii; omat = fextractor.outmatlab; imgres = fextractor.resizeimg; if rg rgi = 0; % fg(1) = fextractor.geostandard; if fg(1) rgi = rgi+1; bg(rgi).name = 'basicgeo'; bg(rgi).options.show = 0; end % fg(2) = fextractor.geoinvariant; if fg(2) rgi = rgi+1; bg(rgi).name = 'hugeo'; bg(rgi).options.show = 0; rgi = rgi+1; bg(rgi).name = 'flusser'; bg(rgi).options.show = 0; end % fg(3) = fextractor.geofourierdes; if fg(3) rgi = rgi+1; bg(rgi).name = 'fourierdes'; bg(rgi).options.show = 0; bg(rgi).options.Nfourierdes = 8; end % fg(4) = fextractor.geoelliptical; if fg(4) rgi = rgi+1; bg(rgi).name = 'fitellipse'; bg(rgi).options.show = 0; end opg.b = bg; end if ri rii = 0; % fi(1) = fextractor.intstandard; if fi(1) rii = rii+1; bi(rii).name = 'basicint'; bi(rii).options.show = 0; end % fi(2) = fextractor.intcontrast; if fi(2) rii = rii+1; bi(rii).name = 'contrast'; bi(rii).options.neighbor = 1; bi(rii).options.param = 1.5; bi(rii).options.show = 0; end % fi(3) = fextractor.intharalick; if fi(3) rii = rii+1; bi(rii).name = 'haralick'; bi(rii).options.dharalick = 1; bi(rii).options.show = 0; rii = rii+1; bi(rii).name = 'haralick'; bi(rii).options.dharalick = 2; bi(rii).options.show = 0; rii = rii+1; bi(rii).name = 'haralick'; bi(rii).options.dharalick = 3; bi(rii).options.show = 0; rii = rii+1; bi(rii).name = 'haralick'; bi(rii).options.dharalick = 4; bi(rii).options.show = 0; rii = rii+1; bi(rii).name = 'haralick'; bi(rii).options.dharalick = 5; bi(rii).options.show = 0; end % fi(4) = fextractor.intfourierdct; if fi(4) rii = rii+1; bi(rii).name = 'fourier'; bi(rii).options.Nfourier = 64; bi(rii).options.Mfourier = 64; bi(rii).options.nfourier = 4; bi(rii).options.mfourier = 4; bi(rii).options.show = 0; rii = rii+1; bi(rii).name = 'dct'; bi(rii).options.Ndct = 64; bi(rii).options.Mdct = 64; bi(rii).options.ndct = 4; bi(rii).options.mdct = 4; bi(rii).options.show = 0; end % fi(5) = fextractor.inthuint; if fi(5) rii = rii+1; bi(rii).name = 'huint'; bi(rii).options.show = 0; end % fi(6) = fextractor.intgabor; if fi(6) rii = rii+1; bi(rii).name = 'gabor'; bi(rii).options.Lgabor = 8; bi(rii).options.Sgabor = 8; bi(rii).options.fhgabor = 2; bi(rii).options.flgabor = 0.1; bi(rii).options.Mgabor = 21; bi(rii).options.show = 0; end % fi(7) = fextractor.intlbp; if fi(7) rii = rii+1; bi(rii).name = 'lbp'; bi(rii).options.vdiv = 1; bi(rii).options.hdiv = 1; bi(rii).options.semantic = 0; bi(rii).options.samples = 8; bi(rii).options.mappingtype = 'u2'; bi(rii).options.show = 0; end if fi(8) rii = rii+1; bi(rii).name = 'hog'; bi(rii).options.ni = 1; bi(rii).options.nj = 1; bi(rii).options.B = 9; bi(rii).options.show = 0; end opi.b = bi; end warning off if ispc switch imgfmt case 2 !dir *.tif/B > imgnames.txt sdir = dir('*.tif'); case 3 !dir *.bmp/B > imgnames.txt sdir = dir('*.bmp'); case 4 !dir *.png/B > imgnames.txt sdir = dir('*.png'); case 5 !dir *.ppm/B > imgnames.txt sdir = dir('*.ppm'); case 6 !dir *.gif/B > imgnames.txt sdir = dir('*.gif'); case 7 !dir *.pbm/B > imgnames.txt sdir = dir('*.pbm'); otherwise !dir *.jpg/B > imgnames.txt sdir = dir('*.jpg'); end else % Asuming unix, ie isunix should be 1 switch imgfmt case 2 !ls *.tif > imgnames.txt sdir = dir('*.tif'); case 3 !ls *.bmp > imgnames.txt sdir = dir('*.bmp'); case 4 !ls *.png > imgnames.txt sdir = dir('*.png'); case 5 !ls *.ppm > imgnames.txt sdir = dir('*.ppm'); case 6 !ls *.png > imgnames.txt sdir = dir('*.png'); case 7 !ls *.pbm > imgnames.txt sdir = dir('*.pbm'); otherwise !ls *.jpg > imgnames.txt sdir = dir('*.jpg'); end end fid = fopen('imgnames.txt','rt'); sdirn = length(sdir); ok = 1; if rg FeatureGeo = []; end if ri neigh = 0; %costr = ['Gray '; 'Red '; 'Green'; 'Blue '; 'Hue '; 'Sat '; 'Value'; 'L '; 'a '; 'b ' ]; costr = 'gRGBHSVLab'; color_str = costr(co==1); %for i=1:10 % if co(i) % s = sprintf('Feature%s = [];',costr(i,:)); % eval(s); % end %end end fall = []; % extracted features falln = []; % feature names imgnames = []; sdiri = 0; while(ok) fsb = Bio_statusbar(sdiri/sdirn,fsb); sdiri = sdiri+1; s = fscanf(fid,'%s\n',[1 1]); if isempty(s) ok = 0; else disp(sprintf('\n\nProcessing image %s...',s)); Io = imread(s); ss = [s ' ']; sname = ss(1:32); %[N,M,P] = size(Io); Io = double(Io); if imgres(1)>0 % k = 2^(imgres+3); % I = imresize(Io,[k k]); mini = min(Io(:)); maxi = max(Io(:)); I = Bim_sat(imresize(Io,imgres),mini,maxi); else I = Io; end [N,M,P] = size(I); % segmentation yes/no [R,E,J] = SegImage(I,seg,pseg,mseg); if sum2(R)==0 if P==3 % 3 channels subplot(2,2,1);imshow(I/256,[]); title(s) else subplot(2,2,1);imshow(Io,[]); title(s) end subplot(2,2,2);imshow(R,[]);title('Segmented Region') str = ['Image ' s ' has no segmentation. The feature extraction will fail. Do you want to segment the whole image?']; yesnoans = questdlg(str, ... 'Bfx_gui: Segmentation Failure', ... 'Yes', 'Abort', 'Abort'); if yesnoans(1)=='Y' R = ones(N,M); end end % switch imgseg % case 1 % [R,E,J] = Bim_segbalu(I); % case 2 % [R,E,J] = Bim_segbalu(I,0.20); % case 3 % [R,E,J] = Bim_segbalu(I,-0.20); % case 4 % [R,E,J] = Bim_segbalu(I); % R = bwlabel(R); % case 5 % [R,E,J] = Bim_segbalu(I,0.20); % R = bwlabel(R); % case 6 % [R,E,J] = Bim_segbalu(I,-0.20); % R = bwlabel(R); % otherwise % R = ones(N,M); % if (P==3) % J = rgb2gray(I); % else % J = I; % end % end % I: imagen a procesar (color or grayvalues) % J: imagen en gray values (transformed or original) % R: segmented image (if no R = ones(N,M) % color vs. grayvalues if (P==3) Imgnow = uint8(round(I)); else Imgnow = I; end ii = find(R==0); if P==3 % 3 channels subplot(2,2,1);imshow(I/256,[]); title(s) Ir = Imgnow(:,:,1); Ig = Imgnow(:,:,2); Ib = Imgnow(:,:,3); else subplot(2,2,1);imshow(Io,[]); title(s) Iw = Imgnow; end if not(isempty(ii)) if (P==3) Ir(ii)=0; Ig(ii)=0; Ib(ii)=0; else Iw(ii) = 0; end end if P==3 Iw = zeros(size(Imgnow)); Iw(:,:,1) = Ir; Iw(:,:,2) = Ig; Iw(:,:,3) = Ib; imshow(uint8(Iw)) else imshow(Iw,[]) end title(s) subplot(2,2,2);imshow(R,[]);title('Segmented Region') pause(0.1) RRR = R; III = I; dpi = fix(N/imgpart); dpj = fix(M/imgpart); fpart = []; fnpart = []; fnimg = []; % feature names fimg = []; % fetaures for this image for parti=1:imgpart for partj=1:imgpart if imgpart > 1 spart = [num2str(parti) num2str(partj)]; else spart = ' '; end fn = []; % feature names fs = []; % extracted features for this partition R = RRR(dpi*(parti-1)+1:dpi*parti,dpj*(partj-1)+1:dpj*partj); I = III(dpi*(parti-1)+1:dpi*parti,dpj*(partj-1)+1:dpj*partj,:); %figure(10) %imshow(I/256,[]) %figure(11) %imshow(III/256,[]) if rg %[NameGeo,Feature,UnitGeo] = geofeatures(R,fg); [Feature,NameGeo] = Bfx_geo(R,opg); %FeatureGeo = [FeatureGeo; Feature]; fn = [fn; NameGeo]; fs = [fs Feature]; end if ri if sum(co(2:4))>0 XRGB = I; end if sum(co(5:7))>0 XHSV = rgb2hsv(I); end if rgblabconv>0 if rgblabconv==1 load LAB XLAB = Bim_rgb2lab(I,M); else XLAB = Bim_rgb2lab0(I); end end color_str = ''; for i=1:10 if co(i) switch i case 1 % Gray if size(I,3)==3 X = rgb2gray(I/256)*256; Xh = uint8(round(X)); else X = double(I); if max(X(:))>256 Xh = uint8(double(X)/256); X = X/256; else Xh = uint8(X); end end case 2 % Red X = XRGB(:,:,1); Xh = uint8(X); case 3 % Green X = XRGB(:,:,2); Xh = uint8(X); case 4 % Blue X = XRGB(:,:,3); Xh = uint8(X); case 5 % H X = XHSV(:,:,1); Xh = double(X); case 6 % S X = XHSV(:,:,2); Xh = double(X); case 7 % V X = XHSV(:,:,3); Xh = uint8(X); case 8 % L* X = XLAB(:,:,1); Xh = double(X)/100; case 9 % a* X = XLAB(:,:,2); Xh = (double(X)+120)/240; case 10 % b* X = XLAB(:,:,3); Xh = (double(X)+120)/240; end opi.colstr = costr(i); [Feature,FeatureName] = Bfx_int(X,R,opi); fn = [fn; FeatureName]; fs = [fs Feature]; subplot(2,2,3);imshow(X,[]);title(['Channel-' costr(i)]) %if (P==3) % subplot(2,2,4);imhist(X);title([costr(i,:) ' Histogram']) %else subplot(2,2,4);imhist(Xh);title(['Histogram-' costr(i)]) %end pause(0) end end end fn = [fn ones(size(fn,1),1)*spart]; fnimg = [fnimg;fn]; % feature names fimg = [fimg fs]; % fetaures for this image for si = 1:size(fs,1) imgnames = [imgnames; sname]; end end end fall = [fall; fimg]; end fnall = fnimg; save % ..backup end f = fall; fn = fnall; fclose(fid); if omat disp('Bfx_gui: saving f (features) and fn (feature names) to Bfx_results.mat...') save Bfx_results f fn imgnames end if oxls % balu2xls disp('Bfx_gui: saving features to Bfx_results.csv (excel compatible)...') csvwrite('Bfx_results.csv',f); disp('Saving feature names in Bfx_guinames.txt...') save Bfx_imgnames.txt fn -ascii end if otxt disp('Bfx_gui: saving features to Bfx_results.txt...') save Bfx_results.txt f -ascii -double disp('Saving feature names in Bfx_guinames.txt...') save Bfx_imgnames.txt fn -ascii end warning on disp(' ') disp(sprintf('Bfx_gui ended successfully: %d features extracted from %d images.',size(f,2),size(f,1))) disp('(all variables saved in matlab.mat as backup)') delete(fsb); % --- Executes on button press in PreviousImage. function PreviousImage_Callback(hObject, eventdata, handles) % hObject handle to PreviousImage (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Nimg sfiles Imgnow nf = length(sfiles); if nf>0 Nimg = Nimg-1; if Nimg<1 Nimg = nf; end Img = imread(sfiles(Nimg).name); Imgnow = Img; subplot(1,1,1); imshow(Img) title(sfiles(Nimg).name) end % --- Executes on button press in NextImage. function NextImage_Callback(hObject, eventdata, handles) % hObject handle to NextImage (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Nimg sfiles Imgnow nf = length(sfiles); if nf>0 Nimg = Nimg+1; if Nimg>length(sfiles) Nimg = 1; end Img = imread(sfiles(Nimg).name); Imgnow = Img; subplot(1,1,1); imshow(Img) title(sfiles(Nimg).name) end % --- Executes on button press in MultipleSegmentation. function MultipleSegmentation_Callback(hObject, eventdata, handles) % hObject handle to MultipleSegmentation (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of MultipleSegmentation global mseg mseg = 1-mseg; % --- Executes on button press in MinusSegmentation. function MinusSegmentation_Callback(hObject, eventdata, handles) % hObject handle to MinusSegmentation (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global pseg mseg seg Imgnow pseg = pseg+0.05; PlotImage(Imgnow,seg,pseg,mseg) % --- Executes on button press in PlusSegmentation. function PlusSegmentation_Callback(hObject, eventdata, handles) % hObject handle to PlusSegmentation (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global pseg mseg seg Imgnow pseg = pseg-0.05; PlotImage(Imgnow,seg,pseg,mseg) % --- Executes on button press in DoSegmentation. function DoSegmentation_Callback(hObject, eventdata, handles) % hObject handle to DoSegmentation (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Imgnow pseg seg mseg PlotImage(Imgnow,seg,pseg,mseg); % --- Executes on button press in IntHOG. function IntHOG_Callback(hObject, eventdata, handles) % hObject handle to IntHOG (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of IntHOG global fextractor fextractor.inthog = get(hObject,'Value');
github
domingomery/Balu-master
Bfx_fourier.m
.m
Balu-master/FeatureExtraction/Bfx_fourier.m
1,916
utf_8
a747d156cb43fd117284995b29b025b5
% [X,Xn,Xu] = Xfourier(I,R,options) % [X,Xn,Xu] = Xfourier(I,options) % % Toolbox Xvis: Fourier features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % Example: % options.Nfourier = 64; % imresize vertical % options.Mfourier = 64; % imresize horizontal % options.mfourier = 2; % imresize frequency vertical % options.nfourier = 2; % imresize frequency horizontal % options.show = 1; % display results % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % J = double(I(:,:,2))/256; % normalized green channel % [X,Xn] = Xfourier(J,R,options); % Fourier features % Bio_printfeatures(X,Xn) % % See also Xharalick, Xclp, Xgabor, Xdct, Xlbp. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [X,Xn] = Xfourier(I,R,options) if nargin==2; options = R; R = ones(size(I)); end I(R==0) = 0; N = options.Nfourier; M = options.Mfourier; n = options.nfourier; m = options.mfourier; N2 = round(N/2); M2 = round(M/2); if options.show disp('--- extracting Fourier features...'); end Im = imresize(double(I),[N M]); FIm = fft2(Im); x = abs(FIm); F = imresize(x(1:N2,1:M2),[n m]); x = angle(FIm); A = imresize(x(1:N2,1:M2),[n m]); LS = 2*n*m; X = zeros(1,LS); Xn = char(zeros(LS,24)); k = 0; for i=1:n for j=1:m k = k + 1; s = sprintf('Fourier Abs (%d,%d) ',i,j); Xn(k,:) = s(1:24); X(k) = F(i,j); end end for i=1:n for j=1:m k = k + 1; s = sprintf('Fourier Ang (%d,%d)[rad] ',i,j); Xn(k,:) = s(1:24); X(k) = A(i,j); end end
github
domingomery/Balu-master
Bfx_hogi.m
.m
Balu-master/FeatureExtraction/Bfx_hogi.m
3,334
utf_8
e85623c068f0196bd52a35b3453bb979
% [X,Xn] = Bfx_hog(I,options) % % Toolbox: Balu % Histogram of Orientated Gradients features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % options.nj; : number of HOG windows per bound box % options.ni : in i (vertical) and j (horizaontal) direction % options.B : number of histogram bins % options.show : show histograms (glyphs) % % Example: % options.nj = 20; % 10 x 20 % options.ni = 10; % histograms % options.B = 9; % 9 bins % options.show = 1; % number of neighbor samples % I = imread('testimg1.jpg'); % input image % J = rgb2gray(I); % figure(1);imshow(J,[]); % figure(2); % [X,Xn] = Bfx_hog(J,options); % HOG features (see gradients % % arround perimeter. % % See also Bfx_phog, Bfx_lbp. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % function [X,Xn,options] = Bfx_hogi(I,R,options) if nargin==2; options = R; R = ones(size(I)); end if ~isfield(options,'normalize') options.normalize = 0; end nj = options.nj; % number of HOG windows per bound box ni = options.ni; % in i (vertical) and j (horizaontal) direction B = options.B; % number of histogram bins show = options.show; % show histograms N = size(I,1); M = size(I,2); X = zeros(1,nj*ni*B); % column vector with zeros I = double(I); dj = floor(M/(nj+1)); di = floor(N/(ni+1)); t = 0; %hj = [-1,0,1]; %hi = -hj'; %Gj = imfilter(I,hj); %Gi = imfilter(I,hi); %A = atan2(Gi,Gj); %A = mod(A,pi); %G = ((Gi.^2)+(Gj.^2)).^.5; G = I(:,:,1)/255*363; A = I(:,:,2)/255*pi; K = 4*di*dj; ang = zeros(K,1); mag = zeros(K,1); if show J = zeros(N,M); ss = min([N/ni M/nj])*0.40; end w = zeros(ni,nj,B); for i = 1:ni ii = (i-1)*di+1:(i+1)*di; i0 = mean(ii); for j = 1:nj jj = (j-1)*dj+1:(j+1)*dj; j0 = mean(jj); t = t+1; ang(:) = A(ii,jj); mag(:) = G(ii,jj); X2 = zeros(B,1); for b = 1:B q = find(ang<=pi*b/B); X2(b) = X2(b)+sum(mag(q)); ang(q) = 5; end X2 = X2/(norm(X2)+0.01); X(1,indices(t,B)) = X2; % w(i,j,:) = X2; if show for b=1:B alpha = pi*b/B; q = -ss:ss; qi = round(i0+q*cos(alpha)); qj = round(j0+q*sin(alpha)); qk = qi+(qj-1)*N; J(qk) = J(qk)+X2(b); end J(round(i0),round(j0))=1; end end end if show imshow(round(J/max2(J)*256),jet) options.J = J; end options.w = w; Xn = char(zeros(nj*ni*B,24)); Xn(:,1) = 'H'; Xn(:,2) = 'O'; Xn(:,3) = 'G'; J = uint8(zeros(N,M,3)); G(G>363) = 363; % max2(Gi) = max2(Gi) = 256 => max2(G) = sqrt(2*256^2) J(:,:,1) = uint8(round(G/363*255)); J(:,:,2) = uint8(round(A/pi*255)); options.Ihog = J; if options.normalize X = X/sum(X); end
github
domingomery/Balu-master
Bfx_fourierdes.m
.m
Balu-master/FeatureExtraction/Bfx_fourierdes.m
1,997
utf_8
3026250f26d693f4384307cb01b351cf
% function [X,Xn] = Bfx_fourierdes(R,options) % % Toolbox: Balu % Computes the Fourier descriptors of a binary image R. % % options.show = 1 display mesagges. % options.Nfourierdes number of descriptors. % % X is the feature vector % Xn is the list of feature names. % % Reference: % Zahn, C; Roskies, R.: Fourier Descriptors for Plane % Closed Curves, IEEE Trans on Computers, C21(3):269-281, 1972 % % Example: % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % [X,Xn] = Bfx_fourierdes(R); % Fourier descriptors % Bio_printfeatures(X,Xn) % % See also Bfx_fitellipse, Bfx_hugeo, Bfx_gupta, Bfx_flusser. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_fourierdes(R,options) if ~exist('options','var') options.show = 0; options.Nfourierdes = 16; end if options.show == 1 disp('--- extracting Fourier descriptors...'); end N = options.Nfourierdes; jj = sqrt(-1); B = bwboundaries(R,'noholes'); g = B{1}; V = g(:,2)+jj*g(:,1); m = size(g,1); r = zeros(m,1); phi = zeros(m,1); dphi = zeros(m,1); l = zeros(m,1); dl = zeros(m,1); r(1) = V(1)-V(m); for i=2:m r(i) = V(i)-V(i-1); end for i=1:m dl(i) = abs(r(i)); phi(i) = angle(r(i)); end for i=1:m-1 dphi(i) = mod(phi(i+1)-phi(i)+pi,2*pi)-pi; end dphi(m) = mod(phi(1)-phi(m)+pi,2*pi)-pi; for k=1:m l(k) = 0; for i=1:k l(k) = l(k) + dl(i); end end L = l(m); A = zeros(N,1); for n=1:N an = 0; bn = 0; for k = 1:m an = an + dphi(k)*sin(2*pi*n*l(k)/L); bn = bn + dphi(k)*cos(2*pi*n*l(k)/L); end an = -an/n/pi; bn = bn/n/pi; imagi = an + jj*bn; A(n) = abs(imagi); end X = A'; Xn = char(zeros(N,24)); for i = 1:N Xn(i,:) = sprintf('Fourier-des %2d ',i); end
github
domingomery/Balu-master
Bfx_contrast.m
.m
Balu-master/FeatureExtraction/Bfx_contrast.m
4,036
utf_8
8019b18ebe9a330ead03c4f53d925a0c
% [X,Xn] = Bfi_contrast(I,R,options) % [X,Xn] = Bfi_contrast(I,options) % % Toolbox: Balu % Contrast features. % % X is the features vector, Xn is the list of feature names(see Example % to see how it works). % % References: % Mery, D.; Filbert: Classification of Potential Defects in % Automated Inspection of Aluminium Castings Using Statistical Pattern % Recognition. In Proceedings of 8th European Conference on Non- % Destructive Testing (ECNDT 2002), Jun. 17-21, 2002, Barcelona, Spain. % % Kamm, K.-F. Ewen, K. (ed.): Grundlagen der R?ntgenabbildung Moderne % Bildgebung: Physik, Ger?tetechnik, Bildbearbeitung und -kommunikation, % Strahlenschutz, Qualit?tskontrolle, Georg Thieme Verlag, 1998, 45-62 % % Example: % options.show = 1; % display results % options.neighbor = 2; % neigborhood is imdilate % options.param = 5; % with 5x5 mask % I = imread('testimg4.jpg'); % input image % J = I(395:425,415:442,1); % region of interest (red) % R = J<=130; % segmentation % figure;imshow(J,[]) % figure;imshow(R) % [X,Xn] = Bfx_contrast(J,R,options); % contrast features % Bio_printfeatures(X,Xn) % % See also Bfx_clp, Bfx_haralick, Bfx_contrast, Bfx_fourier, Bfx_dct, Bfx_lbp. % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_contrast(I,R,options) I = double(I); if nargin==2; options = R; R = ones(size(I)); end if ~isfield(options,'show') options.show = 0; end if options.show == 1 disp('--- extracting contrast features...'); end s = options.param; switch options.neighbor case 1 [N,M] = size(R); [ii,jj] = find(R==1); i_m = mean(ii); j_m = mean(jj); id = (double(max(ii)-min(ii)+1)*s/2); jd = (double(max(jj)-min(jj)+1)*s/2); i1 = max([1 round(i_m-id)]); i2 = min([N round(i_m+id)]); j1 = max([1 round(j_m-jd)]); j2 = min([M round(j_m+jd)]); Rn = zeros(size(R)); Rn(i1:i2,j1:j2)=1; case 2 Rn = imdilate(R,ones(s,s)); [ii,jj] = find(Rn==1); i1 = min(ii); i2 = max(ii); j1 = min(jj); j2 = max(jj); end Rn = and(Rn,not(R)); if sum(Rn(:)) > 0 MeanGr = mean(I(R==1)); MeanGn = mean(I(Rn==1)); K1 = (MeanGr-MeanGn)/MeanGn; % contrast after Kamm, 1999 K2 = (MeanGr-MeanGn)/(MeanGr+MeanGn); % modulation after Kamm, 1999 K3 = log(MeanGr/MeanGn); % film-contrast after Kamm, 1999 else K1 = -1; K2 = -1; K3 = -1; end [Ks,K] = contrast2002(I(i1:i2,j1:j2)); % contrast after Mery Barcelona 2002 XRA0152 X = [K1 K2 K3 Ks K]; Xn = [ 'contrast-K1 ' 'contrast-K2 ' 'contrast-K3 ' 'contrast-Ks ' 'contrast-K ']; end % [Ks,K] = contrast2002(I) % % Toolbox: Balu % Contrast features after Mery & Filbert, 2002. % % D.Mery, PUC-DCC, Apr. 2008 % http://dmery.ing.puc.cl function [Ks,K] = contrast2002(I) [nI,mI] = size(I); n1 = fix(nI/2)+1; m1 = fix(mI/2)+1; P1 = I(n1,:); % Profile in i-Direction P2 = I(:,m1)'; % Profile in j-Direction Q1 = rampefr(P1); % Profile P1 without ramp Q2 = rampefr(P2); % Profile P2 without ramp Q = [Q1 Q2]; % Fusion of profiles Ks = std(Q); % Contrast Ks K = log(max(Q)-min(Q)+1); % Contrast K end % Q = rampefr(P) % % Toolbox: Balu % Eliminate ramp of profile P (used to compute contrast features). % % D.Mery, PUC-DCC, Apr. 2008 % http://dmery.ing.puc.cl function Q = rampefr(P) k = length(P); m = (P(k)-P(1))/(k-1); b = P(1)-m; Q = P - (1:k)*m - b*ones(1,k); end
github
domingomery/Balu-master
Bfx_bsif.m
.m
Balu-master/FeatureExtraction/Bfx_bsif.m
4,662
utf_8
ff6279e64bd0b6798ec5b8c1e69d967f
% [X,Xn,options] = Bfx_bsif(I,R,options) % [X,Xn,options] = Bfx_bsif(I,options) % [X,Xn] = Bfx_bsif(I,R,options) % [X,Xn] = Bfx_bsif(I,options) % % Toolbox: Balu % Binarized statistical image features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % It calculates the BSIF over the a regular grid of patches. The function % uses Juho Kannala and Esa Rahtu (see http://www.ee.oulu.fi/~jkannala/bsif/bsif.html). % % It returns a matrix of uniform bsif descriptors for I, made by % concatenating histograms of each grid cell in the image. % Grid size is options.hdiv * options.vdiv % % R is a binary image or empty. If R is given the bsif will be computed % the corresponding pixles R==0 in image I will be set to 0. % % Output: %%%%%%%%%%%%%%%%%%%%%revisar%%%%%%%%%%%% % X is a matrix of size ((hdiv*vdiv) x 59), each row has a % histogram corresponding to a grid cell. We use 59 bins. % options.x of size hdiv*vdiv is the x coordinates of center of ith grid cell % options.y of size hdiv*vdiv is the y coordinates of center of ith grid cell % Both coordinates are calculated as if image was a square of side length 1. % % References: % J. Kannala and E. Rahtu. Bsif: Binarized statistical image features. % In Pattern Recognition (ICPR), 2012 21st International Conference on, % pages 1363--1366. IEEE, 2012. % % % Example 1: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.filter = 7; % use filter 7x7 % options.bits = 11; % use 11 bits filter % options.mode = 'h'; % return histogram % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % figure(1);imshow(J,[]) % image to be analyzed % [X,Xn] = Bfx_bsif(J,[],options); % BSIF features % figure(2);bar(X) % histogram % % Example 2: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.filter = 7; % use filter 7x7 % options.bits = 11; % use 11 bits filter % options.mode = 'nh'; % return normilized histogram % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % figure(1);imshow(J,[]) % image to be analyzed % [X,Xn] = Bfx_bsif(J,[],options); % BSIF features % figure(2);bar(X) % histogram % % Example 3: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.filter = 7; % use filter 7x7 % options.bits = 11; % use 11 bits filter % options.mode = 'im'; % return image represetation % %(image is only aviable for vdiv = 1 y hdiv = 1) % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % figure(1);imshow(J,[]) % image to be analyzed % [X,Xn] = Bfx_bsif(J,[],options); % BSIF features % figure(2);imshow(X,[]); % display image % % % See also Bfx_lbp, Bfx_gabor, Bfx_clp, Bfx_fourier, Bfx_dct. % % (c) Erick Svec % function [X,Xn] = Bfx_bsif(I,R,options) if nargin==2; options = R; R = ones(size(I)); end vdiv = options.vdiv; hdiv = options.hdiv; if ~isfield(options,'show') options.show = 0; end if options.show == 1 disp('--- extracting binarized statistical image features...'); end filename=['ICAtextureFilters_' int2str(options.filter) 'x' int2str(options.filter) '_' int2str(options.bits) 'bit']; load(filename, 'ICAtextureFilters'); if ~isempty(R); I(R==0) = 0; end if strcmp(options.mode,'im') if vdiv == 1 && hdiv == 1 X = bsif(I,ICAtextureFilters,options.mode); Xn = options; return else throw(MException('MATLAB:odearguments:InconsistentDataType', 'Invalid Options Set: vdiv and hdiv must be 1 for mode im (when try retrieve image representation)')); return end end [N,M] = size(I); w = N/vdiv; h = M/hdiv; X = []; Xn = options; for i = 1:vdiv for j = 1:hdiv part = I(i*w-w+1:w*i,j*h-h+1:h*j); code_img = bsif(part,ICAtextureFilters,options.mode); X = [X code_img]; end end end
github
domingomery/Balu-master
Bfx_randomsliwin.m
.m
Balu-master/FeatureExtraction/Bfx_randomsliwin.m
5,864
utf_8
e8ce09e5cd7d838b6159ae1aa8b838ff
% [X,d,Xn,x] = Bfx_randomsliwin(I,J,options) % % Toolbox: Balu % % Feature extraction of random sliding windows. % This program select automatically detection windows sized mxm % with label '1' and lable '0'. For each window % Balu intensity features are extracted. % % Input: % I original image (more than one channel is allowed) % J ideal segmentation % options.opf feature extraction options (see example) % options.selec selected features, selec = 0 means all features % options.m sliding window size in pixels (mxm) % options.n0 number of '0' windows % options.n1 number of '1' windows % options.ROI region of interest where the windows are extracted % options.th0 if the number of '1' in detection window/m^2 < th0 a '0' % sample is selected % options.th1 if the number of '1' in detection window/m^2 >=th1 a '1' % sample is selected % options.show display detected windows % % Output: % X feature values % Xn feature names % d ideal classification (0 or 1) of each sample % x ceter of mass (j,i) of each patch % % Example: % I1 = imread('testimg7.bmp'); % grayvalue image % [I_on,I2] = Bim_cssalient(I1,1,0); % saliency map % I(:,:,1) = I1; % channel 1 % I(:,:,2) = I2; % cahnnel 2 % J = imread('testimg8.bmp'); % ideal segmentation % bf(1).name = 'lbp'; % definition of % bf(1).options.show = 0; % first features % bf(1).options.vdiv = 1; % bf(1).options.hdiv = 1; % bf(2).name = 'basicint'; % definition of % bf(2).options.show = 0; % second features % bf(2).options.mask = 5; % opf.b = bf; % opf.colstr = 'gs'; % chn 1,2 are gray,sal % options.opf = opf; % options.selec = 0; % all features % options.m = 24; % size of a window mxm % options.n0 = 100; % number of 0 windows % options.n1 = 100; % number of 1 windows % options.th0 = 0.02; % threshold for 0 % options.th1 = 0.02; % threshold for 1 % options.show = 1; % [X,d,Xn] = Bfx_randomsliwin(I,J,options); % % See also Bim_segsliwin. % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function [X,d,Xn,x] = Bfx_randomsliwin(I,J,options) warning off opf = options.opf; % selec = options.selec; m = options.m; % size of a window mxm n0 = options.n0; n1 = options.n1; th0 = options.th0; th1 = options.th1; show = options.show; if isfield(options,'win'); win = options.win; else win = 30; end if isfield(options,'roi'); ROI = options.roi; else ROI = ones(size(I)); end if isfield(options,'selec'); selec = options.selec; else selec = 0; end [N,M]=size(I(:,:,1)); if show==1 close all figure(1) imshow(I(:,:,1),[]);title('Original'); pause(10) hold on %figure(2) %imshow(J);title('Real Defects'); %figure(1) end m1 = m-1; md = (m1-1)/2; m2 = m*m; R = ones(m,m); if show~=-1 ff = Bio_statusbar('Extracting patches'); end ft = Bfx_int(I(1:win,1:win),opf); nf = size(ft,2); % f = []; % x = []; nn = n0+n1; f = zeros(nn,nf); x = zeros(nn,2); d = [zeros(n0,1); ones(n1,1)]; k = 0; if n0>0 % Extracting features for '0' detection windows if show==1 disp('Extracting features for 0 detection windows...'); end i = 0; while i<n0 i1 = fix(rand*(N-m1))+1; j1 = fix(rand*(M-m1))+1; rj = sum2(ROI(i1:i1+m1,j1:j1+m1))/m2; if rj>0.90 wj = J(i1:i1+m1,j1:j1+m1); t = sum(wj(:))/m2; if t<th0 wij = I(i1:i1+m1,j1:j1+m1,:); [ft,fn] = Bfx_int(wij,R,opf); % f = [f;ft 0]; % x = [x;j1+md i1+md]; k = k+1; f(k,:) = ft; x(k,:) = [j1+md i1+md]; i = i+1; if show~=-1 ff = Bio_statusbar(k/nn,ff); end if show==1 % fprintf('0: %d/%d\n',i,n0); plot([j1 j1 j1+m1 j1+m1 j1],[i1 i1+m1 i1+m1 i1 i1],'g') drawnow end end end end end if n1>0 % Extracting features for '1' detection windows if show==1 disp('Extracting features for 1 detection windows...'); end i = 0; while i<n1 i1 = fix(rand*(N-m1))+1; j1 = fix(rand*(M-m1))+1; rj = sum2(ROI(i1:i1+m1,j1:j1+m1))/m2; if rj>0.95 wj = J(i1:i1+m1,j1:j1+m1); t = sum(wj(:))/m2; if t>=th1 wij = I(i1:i1+m1,j1:j1+m1,:); [ft,fn] = Bfx_int(wij,R,opf); % f = [f;ft 1]; % x = [x;j1+md i1+md]; k = k+1; f(k,:) = ft; x(k,:) = [j1+md i1+md]; i = i+1; if show~=-1 ff = Bio_statusbar(k/nn,ff); end if show==1 % fprintf('1: %d/%d\n',i,n1); plot([j1 j1 j1+m1 j1+m1 j1],[i1 i1+m1 i1+m1 i1 i1],'r') drawnow end end end end end if sum(selec)==0 X = f; Xn = fn; else X = f(:,selec); Xn = fn(selec,:); end if show~=-1 delete(ff); end
github
domingomery/Balu-master
Bfx_lbphog.m
.m
Balu-master/FeatureExtraction/Bfx_lbphog.m
1,498
utf_8
35bc94d93b874692e58084e3c10a81e7
% [X,Xn] = Bfx_hog(I,options) % % Toolbox: Balu % Histogram of Orientated Gradients features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % options.nj; : number of HOG windows per bound box % options.ni : in i (vertical) and j (horizaontal) direction % options.B : number of histogram bins % options.show : show histograms (glyphs) % % Example: % options.nj = 20; % 10 x 20 % options.ni = 10; % histograms % options.B = 9; % 9 bins % options.show = 1; % number of neighbor samples % I = imread('testimg1.jpg'); % input image % J = rgb2gray(I); % figure(1);imshow(J,[]); % figure(2); % [X,Xn] = Bfx_hog(J,options); % HOG features (see gradients % % arround perimeter. % % See also Bfx_phog, Bfx_lbp. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % function [X,Xn,options] = Bfx_lbphog(I,R,options) if nargin==2; options = R; R = []; end [X_lbp,Xn_lbp,op_lbp] = Bfx_lbp(I,R,options); [X_hog,Xn_hog,op_hog] = Bfx_hog(I,R,options); I_lbp = op_lbp.Ilbp; I_hog = op_hog.Ihog; X = [X_lbp X_hog ]; Xn = [Xn_lbp; Xn_hog]; N = size(I,1); M = size(I,2); J = uint8(zeros(N,M,3)); J(:,:,1) = I_lbp; J(:,:,2) = I_hog(:,:,1); J(:,:,3) = I_hog(:,:,2); options.Ilbphog = J;
github
domingomery/Balu-master
Bfx_vlhog.m
.m
Balu-master/FeatureExtraction/Bfx_vlhog.m
1,557
utf_8
d708218a0d2591812a418a1ac0eadbdc
% [X,Xn] = Bfx_vlhog(I,options) % % Toolbox: Balu % Histogram of Orientated Gradients features using Vlfeat Toolbox. % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % options.cellsize : size of the cells in pixels % options.variant : 1 for UoCTTI, 2 for Dalal-Triggs % options.show : 1 shows oriented histograms % % Example: % options.cellsize = 32; % 32 x 32 % options.variant = 1; % UoCTTI % options.show = 1; % show results % I = imread('testimg1.jpg'); % input image % J = rgb2gray(I); % figure(1);imshow(J,[]); % figure(2); % [X,Xn] = Bfx_vlhog(J,options); % HOG features (see gradients % % arround perimeter). % % See also Bfx_phog, Bfx_lbp, Bfx_hog, vl_hog. % % (c) GRIMA-DCCUC, 2012 % http://grima.ing.puc.cl % function [X,Xn,options] = Bfx_vlhog(I,R,options) if nargin==2; options = R; R = ones(size(I)); end if ~isfield(options,'variant') options.varian = 1; end if ~isfield(options,'show') options.show = 1; end if options.variant == 1 varname = 'UoCTTI'; else varname = 'DalalTriggs'; end options.hog = vl_hog(im2single(I),options.cellsize,'variant',varname); if options.show==1 figure options.Ir = vl_hog('render',options.hog); imshow(options.Ir,[]); end X = options.hog(:)'; n = length(X); Xn = zeros(n,24);
github
domingomery/Balu-master
Bfx_fitellipse.m
.m
Balu-master/FeatureExtraction/Bfx_fitellipse.m
3,128
utf_8
a1b463a5bd9a20f8037bd3f60f769d2c
% [X,Xn] = Bfx_fitellipse(R,options) % [X,Xn] = Bfx_fitellipse(R) % % Toolbox: Balu % % Fit ellipse for the boundary of a binary image R. % % options.show = 1 display mesagges. % % X is a 6 elements vector: % X(1): Ellipse-centre i direction % X(2): Ellipse-centre j direction % X(3): Ellipse-minor axis % X(4): Ellipse-major axis % X(5): Ellipse-orientation % X(6): Ellipse-eccentricity % X(7): Ellipse-area % % Xn is the list of feature names. % % Xn is the list of feature names. % % Reference: % Fitzgibbon, A.; Pilu, M. & Fisher, R.B. (1999): Direct Least Square % Fitting Ellipses, IEEE Trans. Pattern Analysis and Machine % Intelligence, 21(5): 476-480. % % Example: % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % [X,Xn] = Bfx_fitellipse(R); % ellipse features % Bio_printfeatures(X,Xn) % % See also Bfx_basicgeo, Bfx_hugeo, Bfx_gupta, Bfx_flusser. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_fitellipse(R,options) E = bwperim(R,4); [Y,X] = find(E==1); % pixel of perimeter in (i,j) if length(X)>5 if ~exist('options','var') options.show = 0; end if options.show == 1 disp('--- extracting ellipse features...'); end % normalize data mx = mean(X); my = mean(Y); sx = (max(X)-min(X))/2; sy = (max(Y)-min(Y))/2; x = (X-mx)/sx; y = (Y-my)/sy; % Build design matrix D = [ x.*x x.*y y.*y x y ones(size(x)) ]; [U,S,V] = svd(D); A = V(:,6); % unnormalize a = [ A(1)*sy*sy, ... A(2)*sx*sy, ... A(3)*sx*sx, ... -2*A(1)*sy*sy*mx - A(2)*sx*sy*my + A(4)*sx*sy*sy, ... -A(2)*sx*sy*mx - 2*A(3)*sx*sx*my + A(5)*sx*sx*sy, ... A(1)*sy*sy*mx*mx + A(2)*sx*sy*mx*my + A(3)*sx*sx*my*my ... - A(4)*sx*sy*sy*mx - A(5)*sx*sx*sy*my ... + A(6)*sx*sx*sy*sy ... ]'; a = a/a(6); % get ellipse orientation alpha = atan2(a(2),a(1)-a(3))/2; % get scaled major/minor axes ct = cos(alpha); st = sin(alpha); ap = a(1)*ct*ct + a(2)*ct*st + a(3)*st*st; cp = a(1)*st*st - a(2)*ct*st + a(3)*ct*ct; % get translations T = [[a(1) a(2)/2]' [a(2)/2 a(3)]']; mc = -inv(2*T)*[a(4) a(5)]'; % get scale factor val = mc'*T*mc; scale = abs(1 / (val- a(6))); % get major/minor axis radii ae = 1/sqrt(scale*abs(ap)); be = 1/sqrt(scale*abs(cp)); ecc = ae/be; % eccentricity ar = pi*ae*be; X = [ mc' ae be alpha ecc ar]; else X = [0 0 0 0 0 0 0]; disp('Warning: Bfx_fitellipse does not have enough points to fit'); end Xn = [ 'Ellipse-centre i [px] ' 'Ellipse-centre j [px] ' 'Ellipse-minor ax [px] ' 'Ellipse-major ax [px] ' 'Ellipse-orient [rad] ' 'Ellipse-eccentricity ' 'Ellipse-area [px] ' ];
github
domingomery/Balu-master
Bfx_files.m
.m
Balu-master/FeatureExtraction/Bfx_files.m
8,658
utf_8
b57e06bded6b2d40a2bc7376dab47b76
% [X,Xn,S] = Bfx_files(f,opf) % gemetric and intensity features % [X,Xn,S] = Bfx_files(f,opf,labelling) % features + labelling % % Toolbox: Balu % % Feature extraction from a set of files. % % This function calls feature extraction procedures of all % images defined in f. See example to see how it works. % % X is the feature matrix (one feature per column, one sample per row), % Xn is the list of feature names (see Example to see how it works). % % S is the list of filenames of the images. The features of file S(i,:) % are in row X(i,:). % % Example: % f.path = ''; % current directory or a path directory % f.prefix = 'testimg'; f.extension = '.jpg'; % f.digits = 1; % f.gray = 0; % f.subsample = 1; % f.resize = 1; % f.imgmin = 1; % f.imgmax = 2; % f.window = []; % f.negative = 0; % f.sequence = 1:f.imgmax; % % b(1).name = 'gabor'; b(1).options.show=1; % Gabor features % b(1).options.Lgabor = 8; % number of rotations % b(1).options.Sgabor = 8; % number of dilations (scale) % b(1).options.fhgabor = 2; % highest frequency of interest % b(1).options.flgabor = 0.1; % lowest frequency of interest % b(1).options.Mgabor = 21; % mask size % b(1).options.type = 2; % intensity % % b(2).name = 'basicint'; b(2).options.show = 1; % Basic intensity features % b(2).options.type = 2; % intensity % % b(3).name = 'lbp'; b(3).options.show = 1; % Fourier % b(3).options.vdiv = 2; % vertical div % b(3).options.hdiv = 2; % horizontal div % b(3).options.type = 2; % intensity % % % b(4).name = 'hugeo'; b(4).options.show = 1; % Hu moments % b(4).options.type = 1; % geometric % % b(5).name = 'flusser'; b(5).options.show = 1; % Flusser moments % b(5).options.type = 1; % geometric % % b(6).name = 'fourierdes'; b(6).options.show = 1; % Fourier % b(6).options.Nfourierdes=12; % descriptors % b(6).options.type = 1; % geometric % % opf.b = b; % opf.channels = 'RGB'; % RGB images % opf.segmentation = 'Bim_segbalu'; % segmentation % opf.param = -0.05; % parameters of segmentation % opf.intensity = 1; % % [X,Xn,S] = Bfx_files(f,opf); % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function [X,Xn,S,d] = Bfx_files(f,opf,labeling) if f.imgmax == 0 error('Bfx_files: set of images is empty.') end if ~exist('labeling','var') labeling = 0; end d = zeros(f.imgmax-f.imgmin+1,1); if compare(class(opf.b),'cell')==0 opf.b = Bfx_build(opf.b); end if isfield(opf,'segmentation') doseg = 1; seg = opf.segmentation; if opf.segmentation == 0 doseg = 0; end else doseg = 0; end n = length(opf.b); kg = 0; ki = 0; opg = []; opi = []; for i=1:n if opf.b(i).options.type == 1 kg = kg+1; opg.b(kg) = opf.b(i); else ki = ki+1; opi.b(ki) = opf.b(i); end end X = []; S = []; if doseg if isfield(opf,'param') par = opf.param; else par = []; end end if isfield(opf,'intensity') inten = opf.intensity; else inten = doseg; end ct = 'gRGBHSVLab12'; co = zeros(length(ct),1); if isfield(opf,'channels') ch = opf.channels; if compare(class(ch),'char')==0 colorstr = ch; else % cell colorstr = []; nx = length(ch); for i=1:nx chs = lower(char(ch(i))); switch chs case 'gray' str = 'g'; case 'red' str = 'R'; case 'green' str = 'G'; case 'blue' str = 'B'; case 'hue' str = 'H'; case {'sat','saturation'} str = 'S'; case {'value','val'} str = 'V'; case {'l','l*'} str = 'L'; case {'a','a*'} str = 'a'; case {'b','b*'} str = 'b'; case {'saliency_1','saliency_on'} str = '1'; case {'saliency_2','saliency_off'} str = '2'; end colorstr = [colorstr str]; end end else colorstr = 'g'; end nc = length(colorstr); for i=1:nc opi.colstr = colorstr; ii = ct==colorstr(i); co(ii) = 1; end nc = sum(co); if nc>0 ff = Bio_statusbar('Feature Extraction'); opf.channels = ct(co==1); for i=f.imgmin:f.imgmax ff = Bio_statusbar((i-f.imgmin)/(f.imgmax-f.imgmin+1),ff); Xi = []; Xn = []; [I,st] = Bio_loadimg(f,i); if labeling imshow(I(:,:,1),[]) end [N,M,P] = size(I); IX = zeros(N,M,nc); if sum(co(2:4))>0 XRGB = I; end if sum(co(5:7))>0 XHSV = rgb2hsv(I); end if sum(co(8:10))>0 if (exist('LAB.mat','file')) load LAB XLAB = Bim_rgb2lab(I,M); else disp('Warning: LAB.mat does not exist. CIE formulas will be used for L*a*b conversion'); XLAB = Bim_rgb2lab0(I); end end if sum(co(11:12))>0 [J_on,J_off] = Bim_cssalient(I,1,0); end k = 0; jj = find(co); for ji=1:length(jj) j = jj(ji); k = k + 1; switch j case 1 % Gray if size(I,3)==3 IX(:,:,k) = rgb2gray(I/256)*256; else if max(I(:))>256 IX(:,:,k) = I/256; else IX(:,:,k) = I; end end case 2 % Red IX(:,:,k) = XRGB(:,:,1); case 3 % Green IX(:,:,k) = XRGB(:,:,2); case 4 % Blue IX(:,:,k) = XRGB(:,:,3); case 5 % H IX(:,:,k) = XHSV(:,:,1); case 6 % S IX(:,:,k) = XHSV(:,:,2); case 7 % V IX(:,:,k) = XHSV(:,:,3); case 8 % L* IX(:,:,k) = XLAB(:,:,1); case 9 % a* IX(:,:,k) = XLAB(:,:,2); case 10 % b* IX(:,:,k) = XLAB(:,:,3); case 11 % Saliency on IX(:,:,k) = J_on; case 12 % Saliency on IX(:,:,k) = J_off; end %end end fprintf('\n--- processing image %s...\n',st); if doseg if ~isempty(par) Rg = feval(seg,I,par); else Rg = feval(seg,I); end else Rg = []; end if inten Ri = Rg; else Ri = []; end if ~isempty(opg) if ~isempty(opg.b) [Xgeo,Xng] = Bfx_geo(Rg,opg); Xi = [Xi Xgeo]; Xn = [Xn;Xng]; end end if ~isempty(opi) if ~isempty(opi.b) [Xint,Xni] = Bfx_int(IX,Ri,opi); Xi = [Xi Xint]; Xn = [Xn;Xni]; end end if labeling d(i-f.imgmin+1,1) = input('Label for this image? '); end X = [X;Xi]; st = [st ones(1,200)*' ']; S = [S;st(1:100)]; end delete(ff); else error('Bfx_files error: Colors %s are recognized',colorstr); end
github
domingomery/Balu-master
Bfx_haralick.m
.m
Balu-master/FeatureExtraction/Bfx_haralick.m
6,209
utf_8
08e5cceaeada8d46d9b1ced71e2004ce
% [X,Xn] = Bfx_haralick(I,R,options) % [X,Xn] = Bfx_haralick(I,options) % % Toolbox: Balu % Haralick texture features. % % X is a 28 elements vector with mean and range of mean and range of % % 1 Angular Second Moment % 2 Contrast % 3 Correlacion % 4 Sum of squares % 5 Inverse Difference Moment % 6 Sum Average % 8 Sum Entropy % 7 Sum Variance % 9 Entropy % 10 Difference Variance % 11 Difference Entropy % 12,13 Information Measures of Correlation % 14 Maximal Corrleation Coefficient % % Xn is the list of name features. % % I is the image. R is the binary image that indicates which pixels of I will be % computed. % options.dharalick is the distance in pixels used to compute the % coocurrence matrix. % options.show = 1 display results. % % Reference: % Haralick (1979): Statistical and Structural Approaches to Texture, % Proc. IEEE, 67(5):786-804 % % Example 1: only one distance (3 pixels) % options.dharalick = 3; % 3 pixels distance for coocurrence % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % J = I(:,:,2); % green channel % [X,Xn] = Bfx_haralick(J,R,options); % Haralick features % Bio_printfeatures(X,Xn) % % Example 2: five distances (1,2,...5 pixels) % options.dharalick = 1:5; % 3 pixels distance for coocurrence % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % J = I(:,:,2); % green channel % [X,Xn] = Bfx_haralick(J,R,options); % Haralick features % Bio_printfeatures(X,Xn) % % See also Bfx_gabor, Bfx_clp, Bfx_fourier, Bfx_dct, Bfx_lbp. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl function [X,Xn] = Bfx_haralick(I,R,options) I = double(I); if nargin==2; options = R; R = ones(size(I)); end if isempty(R) R = ones(size(I)); end dseq = options.dharalick; if ~isfield(options,'show') options.show = 0; end if options.show == 1 disp('--- extracting Haralick texture features...'); end m = length(dseq); n = 28*m; X = zeros(1,n); Xn = char(zeros(n,24)); k = 1; for i=1:m d = dseq(i); Cd000 = Bcoocurrencematrix(I, R, d, 0)+Bcoocurrencematrix(I,R, -d, 0);Cd000 = Cd000/sum(Cd000(:)); Cd045 = Bcoocurrencematrix(I, R, d,-d)+Bcoocurrencematrix(I,R, -d, d);Cd045 = Cd045/sum(Cd045(:)); Cd090 = Bcoocurrencematrix(I, R, 0, d)+Bcoocurrencematrix(I,R, 0,-d);Cd090 = Cd090/sum(Cd090(:)); Cd135 = Bcoocurrencematrix(I, R, d, d)+Bcoocurrencematrix(I,R, -d,-d);Cd135 = Cd135/sum(Cd135(:)); TexMat = [Bcoocurrencefeatures(Cd000) Bcoocurrencefeatures(Cd045) Bcoocurrencefeatures(Cd090) Bcoocurrencefeatures(Cd135)]; X(1,i*28-27:i*28) = [mean(TexMat,2); max(abs(TexMat'))']'; for q=1:2 if (q==1) sq = 'mean '; else sq = 'range'; end for s=1:14 Xn(k,:) = sprintf('Tx%2d,d%2d(%s) ',s,d,sq); k = k + 1; end end end end % P = Bcoocurrencematrix(I,R,Io,Jo) % % Coocurrence matrix of the pixels of image I indicated by binary image R % following the direction (Io,Jo). % % (c) D.Mery, PUC-DCC, Apr. 2008 function P = Bcoocurrencematrix(I,R,Io,Jo) V = fix(I/32)+1; [N,M] = size(I); Z1 = zeros(N+40,M+40); Z2 = Z1; R1 = Z1; R2 = R1; Z1(15:N+14,15:M+14) = V; Z2(15+Io:N+14+Io,15+Jo:M+14+Jo) = V; R1(15:N+14,15:M+14) = R; R2(15+Io:N+14+Io,15+Jo:M+14+Jo) = R; ii = find(not(and(R1,R2))); Z1(ii) = -ones(length(ii),1); Z2(ii) = -ones(length(ii),1); T1 = Z1(:); T2 = Z2(:); d = find(and((T1>-1),(T2>-1))); if (not(isempty(d))) P = zeros(8,8); X = sortrows([T1(d) T2(d)]); i1 = find(or(([0; X(:,1)]-[X(:,1); 0]~=0),... ([0; X(:,2)]-[X(:,2); 0]~=0))); i2 = [i1(2:length(i1)); 0]; d = i2-i1; for i=1:length(d)-1 P(X(i1(i),2),X(i1(i),1)) = d(i); end else P = -ones(8,8); end end % Tx = Bcoocurrencefeatures(P) % % Haralick texture features calculated from coocurrence matrix P. % % (c) D.Mery, PUC-DCC, Apr. 2008 function Tx = Bcoocurrencefeatures(P) Pij = P(:); Ng = 8; pxi = sum(P,2); pyj = sum(P)'; ux = mean(pxi); uy = mean(pyj); sx = std(pxi); sy = std(pyj); pxy1 = zeros(2*Ng-1,1); for k=2:2*Ng s = 0; for i=1:Ng for j=1:Ng if (i+j == k) s = s + P(i,j); end end end pxy1(k-1) = s; end pxy2 = zeros(Ng,1); for k=0:Ng-1 s = 0; for i=1:Ng for j=1:Ng if (abs(i-j) == k) s = s + P(i,j); end end end pxy2(k+1) = s; end Q = zeros(Ng,Ng); pxi = pxi+1e-20; pyj = pyj+1e-20; for i=1:Ng for j=1:Ng s = 0; for k=1:Ng s = s + P(i,k)*P(j,k)/pxi(i)/pyj(k); end Q(i,j) = s; end end eigQ = eig(Q); [i,j] = find(P>=0); dif = i-j; dif2 = dif.*dif; dif21 = dif2 + 1; % 1 Angular Second Moment f1 = Pij'*Pij; % 2 Contrast f2 = ((0:Ng-1).*(0:Ng-1))*pxy2; % 3 Correlacion f3 = (sum(i.*j.*Pij)-ux*uy*Ng^2)/sx/sy; % 4 Sum of squares f4 = dif2'*Pij; % 5 Inverse Difference Moment f5 = sum(Pij./dif21); % 6 Sum Average f6 = (2:2*Ng)*pxy1; % 8 Sum Entropy f8 = -pxy1'*log(pxy1+1e-20); % 7 Sum Variance if8 = (2:2*Ng)'-f8; f7 = if8'*pxy1; % 9 Entropy f9 = -Pij'*log(Pij+1e-20); % 10 Difference Variance f10 = var(pxy2); % 11 Difference Entropy f11 = -pxy2'*log(pxy2+1e-20); % 12,13 Information Measures of Correlation HXY = f9; pxipyj = pxi(i).*pyj(j); HXY1 = -Pij'*log(pxipyj+1e-20); HXY2 = -pxipyj'*log(pxipyj+1e-20); HX = -pxi'*log(pxi+1e-20); HY = -pyj'*log(pyj+1e-20); f12 = (HXY-HXY1)/max([HX HY]); f13 = (1-exp(-2*(HXY2-HXY))); % 14 Maximal Corrleation Coefficient f14 = (eigQ(2)); Tx = [f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14]'; end
github
domingomery/Balu-master
Bfx_dct.m
.m
Balu-master/FeatureExtraction/Bfx_dct.m
1,807
utf_8
f7545cce1977db3f89d1e673978c198f
% [X,Xn,] = Bfx_dct(I,R,options) % [X,Xn] = Bfx_dct(I,options) % % Toolbox: Balu % DCT features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % Reference: % Kumar, A.; Pang, G.K.H. (2002): Defect detection in textured materials % using Gabor filters. IEEE Transactions on Industry Applications, % 38(2):425-440. % % Example: % options.Ndct = 64; % imresize vertical % options.Mdct = 64; % imresize horizontal % options.mdct = 2; % imresize frequency vertical % options.ndct = 2; % imresize frequency horizontal % options.show = 1; % display results % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % J = double(I(:,:,2))/256; % normalized green channel % [X,Xn] = Bfx_dct(J,R,options); % dct features % Bio_printfeatures(X,Xn) % % See also Bfx_haralick, Bfx_clp, Bfx_gabor, Bfx_fourier, Bfx_lbp. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_dct(I,R,options) if nargin==2; options = R; R = ones(size(I)); end I(R==0) = 0; N = options.Ndct; M = options.Mdct; n = options.ndct; m = options.mdct; N2 = round(N/2); M2 = round(M/2); if options.show disp('--- extracting dct features...'); end Im = imresize(double(I),[N M]); Fm = abs(dct2(Im)); F = imresize(Fm(1:N2,1:M2),[n m]); LS = n*m; X = zeros(1,LS); Xn = char(zeros(LS,24)); k = 0; for i=1:n for j=1:m k = k + 1; s = sprintf('DCT(%d,%d) ',i,j); Xn(k,:) = s(1:24); X(k) = F(i,j); end end
github
domingomery/Balu-master
Bfx_gaborfull.m
.m
Balu-master/FeatureExtraction/Bfx_gaborfull.m
7,865
utf_8
175cda6c002b920179c6a48331bb5f13
% [X,Xn] = Bfx_gaborfull(I,R,options) % [X,Xn] = Bfx_gaborfull(I,options) % % Toolbox: Balu % Gabor Full features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % Reference: % M. Haghighat, S. Zonouz, M. Abdel-Mottaleb, "CloudID: Trustworthy % cloud-based and cross-enterprise biometric identification," % Expert Systems with Applications, vol. 42, no. 21, pp. 7905-7916, 2015. % % Example: % options.d1 = 4; % factor of downsampling along rows. % options.d2 = 4; % factor of downsampling along columns. % options.u = 5; % number of scales % options.v = 8; % number of orientations % options.mm = 39; % rows of filter bank % options.nn = 39; % columns of filter bank % options.show = 1; % display gabor masks % I = imread('cameraman.tif'); % input image % [X,Xn] = Bfx_gaborfull(I,[],options); % Gabor features % Bio_printfeatures(X(1:10),Xn(1:10,:)) % % See also Bfx_haralick, Bfx_clp, Bfx_fourier, Bfx_dct, Bfx_lbp, Bfx_gabor. % % (c) Functions gaborFilterBank and gaborFeatures were written by Mohammad Haghighat % see credits below. % % (c) D.Mery, PUC-DCC, 2016 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_gaborfull(I,R,options) if nargin==2; options = R; R = ones(size(I)); end if isempty(R) R = ones(size(I)); end if options.show disp('--- extracting Full Gabor features...'); end A = gaborFilterBank(options); % Generates the Gabor filter bank X = gaborFeatures(I,A,R,options); % Generates the Gabor features n = numel(X); Xn = char(zeros(n,24)); for i=1:n Xn(i,:) = sprintf('Gab_%7d ',i); end function featureVector = gaborFeatures(img,gaborArray,R,options) % GABORFEATURES extracts the Gabor features of an input image. % It creates a column vector, consisting of the Gabor features of the input % image. The feature vectors are normalized to zero mean and unit variance. % % % Inputs: % img : Matrix of the input image % gaborArray : Gabor filters bank created by the function gaborFilterBank % d1 : The factor of downsampling along rows. % d2 : The factor of downsampling along columns. % % Output: % featureVector : A column vector with length (m*n*u*v)/(d1*d2). % This vector is the Gabor feature vector of an % m by n image. u is the number of scales and % v is the number of orientations in 'gaborArray'. % % % Sample use: % % img = imread('cameraman.tif'); % gaborArray = gaborFilterBank(5,8,39,39); % Generates the Gabor filter bank % featureVector = gaborFeatures(img,gaborArray,4,4); % Extracts Gabor feature vector, 'featureVector', from the image, 'img'. % % % % Details can be found in: % % M. Haghighat, S. Zonouz, M. Abdel-Mottaleb, "CloudID: Trustworthy % cloud-based and cross-enterprise biometric identification," % Expert Systems with Applications, vol. 42, no. 21, pp. 7905-7916, 2015. % % % % (C) Mohammad Haghighat, University of Miami % [email protected] % PLEASE CITE THE ABOVE PAPER IF YOU USE THIS CODE. if (nargin ~= 4) % Check correct number of arguments error('Please use the correct number of input arguments!') end if size(img,3) == 3 % Check if the input image is grayscale warning('The input RGB image is converted to grayscale!') img = rgb2gray(img); end img = double(img).*R; d1 = options.d1; % factor of downsampling along rows. d2 = options.d2; % factor of downsampling along columns. %% Filter the image using the Gabor filter bank % Filter input image by each Gabor filter [u,v] = size(gaborArray); gaborResult = cell(u,v); for i = 1:u for j = 1:v gaborResult{i,j} = imfilter(img, gaborArray{i,j}); end end %% Create feature vector % Extract feature vector from input image nn = numel(img)/d1/d2; %featureVector = []; featureVector = zeros(1,nn*u*v); t = 0; for i = 1:u for j = 1:v t = t+1; gaborAbs = abs(gaborResult{i,j}); gaborAbs = downsample(gaborAbs,d1); gaborAbs = downsample(gaborAbs.',d2); gaborAbs = gaborAbs(:); % Normalized to zero mean and unit variance. (if not applicable, please comment this line) gaborAbs = (gaborAbs-mean(gaborAbs))/std(gaborAbs,1); %featureVector = [featureVector; gaborAbs]; featureVector(1,indices(t,nn)) = gaborAbs; end end %% Show filtered images (Please comment this section if not needed!) % % Show real parts of Gabor-filtered images % figure('NumberTitle','Off','Name','Real parts of Gabor filters'); % for i = 1:u % for j = 1:v % subplot(u,v,(i-1)*v+j) % imshow(real(gaborResult{i,j}),[]); % end % end % % % Show magnitudes of Gabor-filtered images % figure('NumberTitle','Off','Name','Magnitudes of Gabor filters'); % for i = 1:u % for j = 1:v % subplot(u,v,(i-1)*v+j) % imshow(abs(gaborResult{i,j}),[]); % end % end function gaborArray = gaborFilterBank(options) % GABORFILTERBANK generates a custum Gabor filter bank. % It creates a u by v cell array, whose elements are m by n matrices; % each matrix being a 2-D Gabor filter. % % % Inputs: % u : No. of scales (usually set to 5) % v : No. of orientations (usually set to 8) % m : No. of rows in a 2-D Gabor filter (an odd integer number, usually set to 39) % n : No. of columns in a 2-D Gabor filter (an odd integer number, usually set to 39) % % Output: % gaborArray: A u by v array, element of which are m by n % matries; each matrix being a 2-D Gabor filter % % % Sample use: % % gaborArray = gaborFilterBank(5,8,39,39); % % % % Details can be found in: % % M. Haghighat, S. Zonouz, M. Abdel-Mottaleb, "CloudID: Trustworthy % cloud-based and cross-enterprise biometric identification," % Expert Systems with Applications, vol. 42, no. 21, pp. 7905-7916, 2015. % % % % (C) Mohammad Haghighat, University of Miami % [email protected] % PLEASE CITE THE ABOVE PAPER IF YOU USE THIS CODE. %if (nargin ~= 4) % Check correct number of arguments % error('There must be four input arguments (Number of scales and orientations and the 2-D size of the filter)!') %end %% Create Gabor filters % Create u*v gabor filters each being an m by n matrix u = options.u; % number of scales v = options.v; % number of orientations m = options.mm; % rows of filter bank n = options.nn; % columns of filter bank gaborArray = cell(u,v); fmax = 0.25; gama = sqrt(2); eta = sqrt(2); for i = 1:u fu = fmax/((sqrt(2))^(i-1)); alpha = fu/gama; beta = fu/eta; for j = 1:v tetav = ((j-1)/v)*pi; gFilter = zeros(m,n); for x = 1:m for y = 1:n xprime = (x-((m+1)/2))*cos(tetav)+(y-((n+1)/2))*sin(tetav); yprime = -(x-((m+1)/2))*sin(tetav)+(y-((n+1)/2))*cos(tetav); gFilter(x,y) = (fu^2/(pi*gama*eta))*exp(-((alpha^2)*(xprime^2)+(beta^2)*(yprime^2)))*exp(1i*2*pi*fu*xprime); end end gaborArray{i,j} = gFilter; end end %% Show Gabor filters (Please comment this section if not needed!) if options.show == 1 % Show magnitudes of Gabor filters: figure('NumberTitle','Off','Name','Magnitudes of Gabor filters'); for i = 1:u for j = 1:v subplot(u,v,(i-1)*v+j); imshow(abs(gaborArray{i,j}),[]); end end % Show real parts of Gabor filters: figure('NumberTitle','Off','Name','Real parts of Gabor filters'); for i = 1:u for j = 1:v subplot(u,v,(i-1)*v+j); imshow(real(gaborArray{i,j}),[]); end end end
github
domingomery/Balu-master
Bfx_lbp.m
.m
Balu-master/FeatureExtraction/Bfx_lbp.m
18,701
utf_8
0b6d8f300debf9639dc1a587453b85dc
% [X,Xn,options] = Bfx_lbp(I,R,options) % [X,Xn,options] = Bfx_lbp(I,options) % [X,Xn] = Bfx_lbp(I,R,options) % [X,Xn] = Bfx_lbp(I,options) % % Toolbox: Balu % Local Binary Patterns features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % It calculates the LBP over the a regular grid of patches. The function % uses Heikkila & Ahonen (see http://www.cse.oulu.fi/MVG/Research/LBP). % % It returns a matrix of uniform lbp82 descriptors for I, made by % concatenating histograms of each grid cell in the image. % Grid size is options.hdiv * options.vdiv % % R is a binary image or empty. If R is given the lbp will be computed % the corresponding pixles R==0 in image I will be set to 0. % % Output: % X is a matrix of size ((hdiv*vdiv) x 59), each row has a % histogram corresponding to a grid cell. We use 59 bins. % options.x of size hdiv*vdiv is the x coordinates of center of ith grid cell % options.y of size hdiv*vdiv is the y coordinates of center of ith grid cell % Both coordinates are calculated as if image was a square of side length 1. % % References: % Ojala, T.; Pietikainen, M. & Maenpaa, T. Multiresolution gray-scale % and rotation invariant texture classification with local binary % patterns. IEEE Transactions on Pattern Analysis and Machine % Intelligence, 2002, 24, 971-987. % % Mu, Y. et al (2008): Discriminative Local Binary Patterns for Human % Detection in Personal Album. CVPR-2008. % % Example 1: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 0; % classic LBP % options.samples = 8; % number of neighbor samples % options.mappingtype = 'u2'; % uniform LBP % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % figure(1);imshow(J,[]) % image to be analyzed % [X,Xn] = Bfx_lbp(J,[],options); % LBP features % figure(2);bar(X) % histogram % % Example 2: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 0; % classic LBP % options.samples = 8; % number of neighbor samples % options.mappingtype = 'ri'; % rotation-invariant LBP % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % figure(1);imshow(J,[]) % image to be analyzed % [X,Xn] = Bfx_lbp(J,[],options); % LBP features % bar(X) % histogram % % Example 3: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 8; % number of neighbor samples % options.sk = 0.5; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % semantic LBP features % bar(X) % histogram % % Example 4: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 16; % number of neighbor samples % options.sk = 0.5; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % semantic LBP features % bar(X) % histogram % % Example 5: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 8; % number of neighbor samples % options.sk = 0.25; % angle sampling % options.weight = 9; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % weighted LBP features % bar(X) % histogram % See also Bfx_gabor, Bfx_clp, Bfx_fourier, Bfx_dct. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % % James Kapaldo updated this version for Matlab2014b % function [X,Xn,options] = Bfx_lbp(I,R,options) if nargin==2; options = R; R = ones(size(I)); end vdiv = options.vdiv; hdiv = options.hdiv; if ~isfield(options,'show') options.show = 0; end if ~isfield(options,'normalize') options.normalize = 0; end if options.show == 1 disp('--- extracting local binary patterns features...'); end if ~isfield(options,'samples') options.samples = 8; end if ~isfield(options,'integral') options.integral = 0; end if ~isfield(options,'radius') options.radius = log(options.samples)/log(2)-1; end if ~isfield(options,'semantic') options.semantic = 0; end if ~isfield(options,'weight') options.weight = 0; end LBPst = 'LBP'; if options.semantic>0 if ~isfield(options,'sk') options.sk = 1; end mapping = getsmapping(options.samples,options.sk); LBPst = ['s' LBPst]; st='8x8'; else % mapping = getmapping(8,'u2'); if ~isfield(options,'mappingtype') options.mappingtype = 'u2'; end st = sprintf('%d,%s',options.samples,options.mappingtype); mapping = getmapping(options.samples,options.mappingtype); end % get lbp image if ~isempty(R); I(R==0) = 0; end code_img = lbp(I,options.radius,options.samples,mapping,''); [n1,n2] = size(code_img); [N,M] = size(I); Ilbp = zeros(size(I)); i1 = round((N-n1)/2); j1 = round((M-n2)/2); Ilbp(i1+1:i1+n1,j1+1:j1+n2) = code_img; options.Ilbp = Ilbp; if options.integral == 1 options.Hx = Bim_inthist(Ilbp+1,options.maxD); end ylen = round(n1/vdiv); xlen = round(n2/hdiv); % split image into blocks (saved as columns) grid_img = im2col(code_img,[ylen, xlen], 'distinct'); if options.weight>0 LBPst = ['w' LBPst]; mt = 2*options.radius-1; mt2 = mt^2; Id = double(I); switch options.weight case 1 W = abs(conv2(Id,ones(mt,mt)/mt2,'same')-Id); case 2 W = (abs(conv2(Id,ones(mt,mt)/mt2,'same')-Id))./(Id+1); case 3 W = abs(medfilt2(Id,[mt mt])-Id); case 4 W = abs(medfilt2(Id,[mt mt])-Id)./(Id+1); case 5 W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id); case 6 W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id)./(Id+1); case 7 Id = conv2(Id,ones(mt,mt)/mt2,'same'); W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id)./(Id+1); case 8 Id = medfilt2(Id,[mt mt]); W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id)./(Id+1); case 9 Id = medfilt2(Id,[mt mt]); W = abs(ordfilt2(Id,mt2-1,ones(mt,mt))-Id)./(Id+1); otherwise error('Bfx_lbp does not recognice options.weight = %d.',options.weight); end W = W(mt+1:end-mt,mt+1:end-mt); grid_W = im2col(W,[ylen, xlen], 'distinct'); nwi = mapping.num; nwj = size(grid_W,2); nwk = size(grid_W,1); desc = zeros(nwi,nwj); for j=1:nwj x = grid_img(:,j)+1; y = grid_W(:,j); d = zeros(nwi,1); for k=1:nwk d(x(k))=d(x(k))+y(k); % d(x(k))=d(x(k))+1; % normal LBP each LBP has equal weight end desc(:,j) = d; end else desc = hist(double(grid_img), 0:mapping.num-1); % calculate coordinates of descriptors as if I was square w/ side=1 end dx = 1.0/hdiv; dy = 1.0/vdiv; x = dx/2.0: dx :1.0-dx/2.0; y = dy/2.0: dy :1.0-dy/2.0; options.x = x; options.y = y; if hdiv*vdiv>1 D = desc'; else D = desc; end [M,N] = size(D); Xn = char(zeros(N*M,24)); X = zeros(1,N*M); k=0; for i=1:M for j=1:N k = k+1; s = sprintf('%s(%d,%d)[%s] ',LBPst,i,j,st); Xn(k,:) = s(1:24); X(k) = D(i,j); end end if options.normalize X = X/sum(X); end end %GETMAPPING returns a structure containing a mapping table for LBP codes. % MAPPING = GETMAPPING(SAMPLES,MAPPINGTYPE) returns a % structure containing a mapping table for % LBP codes in a neighbourhood of SAMPLES sampling % points. Possible values for MAPPINGTYPE are % 'u2' for uniform LBP % 'ri' for rotation-invariant LBP % 'riu2' for uniform rotation-invariant LBP. % % Example: % I=imread('rice.tif'); % MAPPING=getmapping(16,'riu2'); % LBPHIST=lbp(I,2,16,MAPPING,'hist'); % Now LBPHIST contains a rotation-invariant uniform LBP % histogram in a (16,2) neighbourhood. % function mapping = getmapping(samples,mappingtype) % Version 0.1.1 % Authors: Marko Heikkila and Timo Ahonen % Changelog % 0.1.1 Changed output to be a structure % Fixed a bug causing out of memory errors when generating rotation % invariant mappings with high number of sampling points. % Lauge Sorensen is acknowledged for spotting this problem. table = 0:2^samples-1; newMax = 0; %number of patterns in the resulting LBP code index = 0; %vr2014b = or(strcmp(version('-release'),'2014b'),strcmp(version('-release'),'2014a')); %if vr2014b switch samples case 8 sampleType = 'uint8'; case 16 sampleType = 'uint16'; otherwise end %else % sampleType = samples; %end if strcmp(mappingtype,'u2') %Uniform 2 newMax = samples*(samples-1) + 3; for i = 0:2^samples-1 j = bitset(bitshift(i,1,sampleType),1,bitget(i,samples)); %rotate left numt = sum(bitget(bitxor(i,j),1:samples)); %number of 1->0 and %0->1 transitions %in binary string %x is equal to the %number of 1-bits in %XOR(x,Rotate left(x)) if numt <= 2 table(i+1) = index; index = index + 1; else table(i+1) = newMax - 1; end end end if strcmp(mappingtype,'ri') %Rotation invariant tmpMap = zeros(2^samples,1) - 1; for i = 0:2^samples-1 rm = i; r = i; for j = 1:samples-1 r = bitset(bitshift(r,1,sampleType),1,bitget(r,samples)); %rotate %left if r < rm rm = r; end end if tmpMap(rm+1) < 0 tmpMap(rm+1) = newMax; newMax = newMax + 1; end table(i+1) = tmpMap(rm+1); end end if strcmp(mappingtype,'riu2') %Uniform & Rotation invariant newMax = samples + 2; for i = 0:2^samples - 1 j = bitset(bitshift(i,1,sampleType),1,bitget(i,samples)); %rotate left numt = sum(bitget(bitxor(i,j),1:samples)); if numt <= 2 table(i+1) = sum(bitget(i,1:samples)); else table(i+1) = samples+1; end end end mapping.table=table; mapping.samples=samples; mapping.num=newMax; end % LBP returns the local binary pattern image or LBP histogram of an image. % J = LBP(I,R,N,MAPPING,MODE) returns either a local binary pattern % coded image or the local binary pattern histogram of an intensity % image I. The LBP codes are computed using N sampling points on a % circle of radius R and using mapping table defined by MAPPING. % See the getmapping function for different mappings and use 0 for % no mapping. Possible values for MODE are % 'h' or 'hist' to get a histogram of LBP codes % 'nh' to get a normalized histogram % Otherwise an LBP code image is returned. % % J = LBP(I) returns the original (basic) LBP histogram of image I % % J = LBP(I,SP,MAPPING,MODE) computes the LBP codes using n sampling % points defined in (n * 2) matrix SP. The sampling points should be % defined around the origin (coordinates (0,0)). % % Examples % -------- % I=imread('rice.png'); % mapping=getmapping(8,'u2'); % H1=LBP(I,1,8,mapping,'h'); %LBP histogram in (8,1) neighborhood % %using uniform patterns % subplot(2,1,1),stem(H1); % % H2=LBP(I); % subplot(2,1,2),stem(H2); % % SP=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1]; % I2=LBP(I,SP,0,'i'); %LBP code image using sampling points in SP % %and no mapping. Now H2 is equal to histogram % %of I2. function result = lbp(varargin) % image,radius,neighbors,mapping,mode) % Version 0.3.2 % Authors: Marko Heikkila and Timo Ahonen % Changelog % Version 0.3.2: A bug fix to enable using mappings together with a % predefined spoints array % Version 0.3.1: Changed MAPPING input to be a struct containing the mapping % table and the number of bins to make the function run faster with high number % of sampling points. Lauge Sorensen is acknowledged for spotting this problem. % Check number of input arguments. narginchk(1,5); % error(nargchk(1,5,nargin)); % for previous versions of matlab image=varargin{1}; d_image=double(image); if nargin==1 spoints=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1]; neighbors=8; mapping=0; mode='h'; end if (nargin == 2) && (length(varargin{2}) == 1) error('Input arguments'); end if (nargin > 2) && (length(varargin{2}) == 1) radius=varargin{2}; neighbors=varargin{3}; spoints=zeros(neighbors,2); % Angle step. a = 2*pi/neighbors; for i = 1:neighbors spoints(i,1) = -radius*sin((i-1)*a); spoints(i,2) = radius*cos((i-1)*a); end if(nargin >= 4) mapping=varargin{4}; if(isstruct(mapping) && mapping.samples ~= neighbors) error('Incompatible mapping'); end else mapping=0; end if(nargin >= 5) mode=varargin{5}; else mode='h'; end end if (nargin > 1) && (length(varargin{2}) > 1) spoints=varargin{2}; neighbors=size(spoints,1); if(nargin >= 3) mapping=varargin{3}; if(isstruct(mapping) && mapping.samples ~= neighbors) error('Incompatible mapping'); end else mapping=0; end if(nargin >= 4) mode=varargin{4}; else mode='h'; end end % Determine the dimensions of the input image. [ysize xsize] = size(image); miny=min(spoints(:,1)); maxy=max(spoints(:,1)); minx=min(spoints(:,2)); maxx=max(spoints(:,2)); % Block size, each LBP code is computed within a block of size bsizey*bsizex bsizey=ceil(max(maxy,0))-floor(min(miny,0))+1; bsizex=ceil(max(maxx,0))-floor(min(minx,0))+1; % Coordinates of origin (0,0) in the block origy=1-floor(min(miny,0)); origx=1-floor(min(minx,0)); % Minimum allowed size for the input image depends % on the radius of the used LBP operator. if(xsize < bsizex || ysize < bsizey) error('Too small input image. Should be at least (2*radius+1) x (2*radius+1)'); end % Calculate dx and dy; dx = xsize - bsizex; dy = ysize - bsizey; % Fill the center pixel matrix C. C = image(origy:origy+dy,origx:origx+dx); d_C = double(C); bins = 2^neighbors; % Initialize the result matrix with zeros. result=zeros(dy+1,dx+1); %Compute the LBP code image for i = 1:neighbors y = spoints(i,1)+origy; x = spoints(i,2)+origx; % Calculate floors, ceils and rounds for the x and y. fy = floor(y); cy = ceil(y); ry = round(y); fx = floor(x); cx = ceil(x); rx = round(x); % Check if interpolation is needed. if (abs(x - rx) < 1e-6) && (abs(y - ry) < 1e-6) % Interpolation is not needed, use original datatypes N = image(ry:ry+dy,rx:rx+dx); D = N >= C; else % Interpolation needed, use double type images ty = y - fy; tx = x - fx; % Calculate the interpolation weights. w1 = (1 - tx) * (1 - ty); w2 = tx * (1 - ty); w3 = (1 - tx) * ty ; w4 = tx * ty ; % Compute interpolated pixel values N = w1*d_image(fy:fy+dy,fx:fx+dx) + w2*d_image(fy:fy+dy,cx:cx+dx) + ... w3*d_image(cy:cy+dy,fx:fx+dx) + w4*d_image(cy:cy+dy,cx:cx+dx); D = N >= d_C; end % Update the result matrix. v = 2^(i-1); result = result + v*D; end %Apply mapping if it is defined if isstruct(mapping) bins = mapping.num; for i = 1:size(result,1) for j = 1:size(result,2) result(i,j) = mapping.table(result(i,j)+1); end end end if (strcmp(mode,'h') || strcmp(mode,'hist') || strcmp(mode,'nh')) % Return with LBP histogram if mode equals 'hist'. result=hist(result(:),0:(bins-1)); if (strcmp(mode,'nh')) result=result/sum(result); end else %Otherwise return a matrix of unsigned integers if ((bins-1)<=intmax('uint8')) result=uint8(result); elseif ((bins-1)<=intmax('uint16')) result=uint16(result); else result=uint32(result); end end end % Mapping for sLBB function mapping = getsmapping(N,sk) vr2014b = or(strcmp(version('-release'),'2014b'),strcmp(version('-release'),'2014a')); if vr2014b switch N case 8 sampleType = 'uint8'; case 16 sampleType = 'uint16'; otherwise end else sampleType = samples; end M = 2^N; samples = N; len = zeros(M,1); ang = zeros(M,1); for x=0:(M-1) k = x+1; j = bitset(bitshift(x,1,sampleType),1,bitget(x,samples)); numt = sum(bitget(bitxor(x,j),1:samples)); c = numt; if c>2 len(k)=-1; ang(k)=-1; else s = bitget(x,1:samples); len(k) = sum(s); if c==0 ang(k)=0; else r = 0; while (s(1)~=0) || (s(N)~=1) s = [s(2:N) s(1)]; r = r+1; end ii = find(s==1); a = mean(ii)+r; if a>N a=a-N; end ang(k) = round(sk*a)-1; end end % fprintf('%4d: %s (%d,%d)\n',x,dec2bin(x,N),len(k),ang(k)); pause end Ma = max(ang)+1; map = len*Ma+ang-Ma+1; n = max(map)+1; map(ang==-1) = n; map(1) = 0; mapping.table = map'; mapping.samples = N; mapping.num = n+1; end
github
domingomery/Balu-master
Bfx_lbpcontrast.m
.m
Balu-master/FeatureExtraction/Bfx_lbpcontrast.m
1,609
utf_8
44e9e37cce48e0b0ab58dbb5c1aa27f0
% Pietikainen, M. et al (2011): Computer Vision Using Local Binary % Patterns, Springer. function J = Bfx_lbpcontrast(I,options) if ~exist('options','var') m = 3; else m = options.m; end n = (m-1)/2; [N,M,P] = size(I); if P==1 % 2D m0 = (m^2+1)/2; ii = [1:m0-1 m0+1:m^2]; J = zeros(N,M); for i=n+1:N-n for j=n+1:M-n s = I(i-n:i+n,j-n:j+n); if std2(s)>0 st = s(ii); it = st>=s(m0); Jplus = mean(st(it)); Jminus = mean(st(not(it))); if isnan(Jplus) Jplus = 0; Jminus = 0; end if isnan(Jminus) Jminus = 0; Jplus = 0; end J(i,j) = Jplus-Jminus; end end end else m0 = (m^3+1)/2; ii = [1:m0-1 m0+1:m^3]; J = zeros(N,M,P); for i=n+1:N-1 for j=n+1:M-1 for k=n+1:P-1 s = I(i-n:i+n,j-n:j+n,k-n:k+n); if std2(s)>0 st = s(ii); it = st>=s(m0); Jplus = mean(st(it)); Jminus = mean(st(not(it))); if isnan(Jplus) Jplus = 0; Jminus = 0; end if isnan(Jminus) Jminus = 0; Jplus = 0; end J(i,j,k) = Jplus-Jminus; end end end end end
github
domingomery/Balu-master
Bfx_flusser.m
.m
Balu-master/FeatureExtraction/Bfx_flusser.m
2,208
utf_8
05663d5a0b328c25995959249565bdf2
% [X,Xn] = Bfx_flusser(R,options) % [X,Xn] = Bfx_flusser(R) % % Toolbox: Balu % % Extract the four Flusser moments from binary image R. % % options.show = 1 display mesagges. % % X is a 4 elements vector: % X(i): Flusser-moment i for i=1,...,4. % Xn is the list of feature names. % % Reference: % Sonka et al. (1998): Image Processing, Analysis, and Machine Vision, % PWS Publishing. Pacific Grove, Ca, 2nd Edition. % % Example: % I = imread('testimg3.jpg'); % input image % R = Bim_segbalu(I); % segmentation % [L,n] = bwlabel(R); % regions % imshow(L,[]) % X = []; % for i=1:n % [Xi,Xn] = Bfx_flusser(L==i); % Flusser moments % X = [X;Xi]; % end % X % % See also Bfx_standard, Bfx_hugeo, Bfx_fitellipse, Bfx_gupta. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_flusser(R,options) if ~exist('options','var') options.show = 0; end if options.show == 1 disp('--- extracting Flusser moments...'); end [Ireg,Jreg] = find(R==1); % pixels in the region i_m = mean(Ireg); j_m = mean(Jreg); A = length(Ireg); I0 = ones(A,1); J0 = ones(A,1); I1 = Ireg - i_m*ones(A,1); J1 = Jreg - j_m*ones(A,1); I2 = I1.*I1; J2 = J1.*J1; I3 = I2.*I1; J3 = J2.*J1; % Central moments u00 = (I0'*J0); % u01 = (I0'*J1); not used u02 = (I0'*J2); u03 = (I0'*J3); % u10 = (I1'*J0); not used u20 = (I2'*J0); u30 = (I3'*J0); u11 = (I1'*J1); u12 = (I1'*J2); u21 = (I2'*J1); II1 = (u20*u02-u11^2)/u00^4 ; II2 = (u30^2*u03^2-6*u30*u21*u12*u03+4*u30*u12^3+4*u21^3*u03-3*u21^2*u12^2)/u00^10; II3 = (u20*(u21*u03-u12^2)-u11*(u30*u03-u21*u12)+u02*(u30*u12-u21^2))/u00^7; II4 = (u20^3*u03^2-6*u20^2*u11*u12*u03-6*u20^2*u02*u21*u03+9*u20^2*u02*u12^2 + 12*u20*u11^2*u21*u03+6*u20*u11*u02*u30*u03-18*u20*u11*u02*u21*u12-8*u11^3*u30*u03- 6*u20*u02^2*u30*u12+9*u20*u02^2*u21+12*u11^2*u02*u30*u12-6*u11*u02^2*u30*u21+u02^3*u30^2)/u00^11; X = [II1 II2 II3 II4]; Xn = [ 'Flusser-moment 1 ' 'Flusser-moment 2 ' 'Flusser-moment 3 ' 'Flusser-moment 4 '];
github
domingomery/Balu-master
Bfx_phog.m
.m
Balu-master/FeatureExtraction/Bfx_phog.m
4,705
utf_8
76718a146565c533700f9b922c118f81
% [X,Xn,Xu] = Bfx_phog(I,R,options) % [X,Xn,Xu] = Bfx_phog(I,options) % % Toolbox: Balu % % Pyramid Histogram of Oriented Gradients based on implementation by % Anna Bosch from % % http://www.robots.ox.ac.uk/~vgg/research/caltech/phog.html % % IN: % I - Images of size MxN (Color or Gray) % options.bin - Number of bins on the histogram % options.L - number of pyramid levels % % OUT: % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % Reference: % Dalal, N. & Triggs, B. (2005): Histograms of oriented gradients for % human detection, Proceedings of the Conference on Computer Vision and % Pattern Recognition, Vol. 1, 886-893 % % Example: % options.bin = 9; % bins on the histogram % options.L = 3; % pyramides levels % options.show = 1; % display results % I = imread('testimg1.jpg'); % input image % J = double(I(:,:,2))/256; % normalized green channel % [X,Xn] = Bfx_phog(J,options); % phog features % Bio_printfeatures(X,Xn) % % See also Bfx_haralick, Bfx_clp, Bfx_gabor, Bfx_fourier, Bfx_lbp. % % D.Mery, A. Soto PUC-DCC, Jun. 2010 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_phog(I,R,options) if nargin==2; options = R; R = ones(size(I)); end I(R==0) = 0; bin = options.bin; L = options.L; if options.show disp('--- extracting phog features...'); end roi = [1 size(I,1) 1 size(I,2)]'; angle = 360; if size(I,3) == 3 G = rgb2gray(I); else G = I; end if sum(sum(G))>100 E = edge(G,'canny'); [GradientX,GradientY] = gradient(double(G)); Gr = sqrt((GradientX.*GradientX)+(GradientY.*GradientY)); index = GradientX == 0; GradientX(index) = 1e-5; A = ((atan2(GradientY,GradientX)+pi)*180)/pi; [bh bv] = BphogbinMatrix(A,E,Gr,angle,bin); else bh = zeros(size(I,1),size(I,2)); bv = zeros(size(I,1),size(I,2)); end bh_roi = bh(roi(1,1):roi(2,1),roi(3,1):roi(4,1)); bv_roi = bv(roi(1,1):roi(2,1),roi(3,1):roi(4,1)); X = BphogDescriptor(bh_roi,bv_roi,L,bin)'; n = length(X); Xn = char(zeros(n,24)); for i=1:n s = sprintf('phog(%d) ',i); Xn(i,:) = s(1:24); end end function p = BphogDescriptor(bh,bv,L,bin) % anna_PHOGDESCRIPTOR Computes Pyramid Histogram of Oriented Gradient over a ROI. % % Pyramid Histogram of Oriented Gradients based on implementation by % Anna Bosch from % % http://www.robots.ox.ac.uk/~vgg/research/caltech/phog.html % %IN: % bh - matrix of bin histogram values % bv - matrix of gradient values % L - number of pyramid levels % bin - number of bins % %OUT: % p - pyramid histogram of oriented gradients (phog descriptor) p = []; for b=1:bin ind = bh==b; p = [p;sum(bv(ind))]; end cella = 1; for l=1:L x = fix(size(bh,2)/(2^l)); y = fix(size(bh,1)/(2^l)); xx=0; yy=0; while xx+x<=size(bh,2) while yy +y <=size(bh,1) bh_cella = bh(yy+1:yy+y,xx+1:xx+x); bv_cella = bv(yy+1:yy+y,xx+1:xx+x); for b=1:bin ind = bh_cella==b; p = [p;sum(bv_cella(ind))]; end yy = yy+y; end cella = cella+1; yy = 0; xx = xx+x; end end if sum(p)~=0 p = p/sum(p); end end function [bm bv] = BphogbinMatrix(A,E,G,angle,bin) % anna_BINMATRIX Computes a Matrix (bm) with the same size of the image where % (i,j) position contains the histogram value for the pixel at position (i,j) % and another matrix (bv) where the position (i,j) contains the gradient % value for the pixel at position (i,j) % % Pyramid Histogram of Oriented Gradients based on implementation by % Anna Bosch from % % http://www.robots.ox.ac.uk/~vgg/research/caltech/phog.html % % %IN: % A - Matrix containing the angle values % E - Edge Image % G - Matrix containing the gradient values % angle - 180 or 360% % bin - Number of bins on the histogram % angle - 180 or 360 %OUT: % bm - matrix with the histogram values % bv - matrix with the graident values (only for the pixels belonging to % and edge) [contorns,n] = bwlabel(E); X = size(E,2); Y = size(E,1); bm = zeros(Y,X); bv = zeros(Y,X); nAngle = angle/bin; for i=1:n [posY,posX] = find(contorns==i); for j=1:size(posY,1) pos_x = posX(j,1); pos_y = posY(j,1); b = ceil(A(pos_y,pos_x)/nAngle); if b==0, bin= 1; end if G(pos_y,pos_x)>0 bm(pos_y,pos_x) = b; bv(pos_y,pos_x) = G(pos_y,pos_x); end end end end
github
domingomery/Balu-master
Bfx_clp_old.m
.m
Balu-master/FeatureExtraction/Bfx_clp_old.m
4,664
utf_8
c8bae5401c7b894bb426467bef73f207
% [X,Xn] = Bfx_clp(I,R,options) % [X,Xn] = Bfx_clp(I,options) % % Toolbox: Balu % Crossing Line Profile. % % X is the features vector, Xn is the list of feature names(see Example % to see how it works). % % Reference: % Mery, D.: Crossing line profile: a new approach to detecting defects % in aluminium castings. Proceedings of the Scandinavian Conference on % Image Analysis 2003 (SCIA 2003), Lecture Notes in Computer Science % LNCS 2749: 725-732, 2003. % % Example: % options.show = 1; % display results % options.ng = 32; % windows resize % I = imread('testimg4.jpg'); % input image % J = I(395:425,415:442,1); % region of interest (red) % R = J>135; % segmentation % figure;imshow(J,[]) % figure;imshow(R) % [X,Xn] = Bfx_clp(J,R,options); % CLP features % Bio_printfeatures(X,Xn) % % See also Bfx_contrast, Bfx_haralick, Bfx_clp, Bfx_fourier, Bfx_dct, Bfx_lbp. % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_clp(I,R,options) I = double(I); if nargin==2; options = R; R = ones(size(I)); end if ~isfield(options,'show') options.show = 0; end if options.show == 1 disp('--- extracting Crossing line profile features...'); end show = options.show; if ~isempty(R); I(R==0) = 0; end ng = options.ng; Bn = imresize(I,[ng ng]); mg = fix(ng/2+1); % Crossing line profiles P0 = Bn(mg,:)'; % 0.0 ... 90.0 4 P1 = Bn(:,mg); % 90.0 ... 0.0 0 P2 = zeros(ng,1); % 45.0 ... 135.0 6 P3 = zeros(ng,1); % 135.0 ... 45.0 2 P4 = zeros(ng,1); % 22.5 ... 112.5 5 P5 = zeros(ng,1); % 67.5 ... 157.5 7 P6 = zeros(ng,1); % 112.5 ... 22.5 1 P7 = zeros(ng,1); % 157.5 ... 67.5 3 Q0 = Bn; Q1 = Bn; Q2 = Bn; Q3 = Bn; Q4 = Bn; Q5 = Bn; Q6 = Bn; Q7 = Bn; Q0(mg,:) = 255*ones(1,ng); Q1(:,mg) = 255*ones(ng,1); m4 = mg/(ng-1); b4 = mg/2-m4; b7 = 3*mg/2+mg/(ng-1); for i=1:ng P2(i,1) = Bn(i,i); Q2(i,i) = 255; P3(i,1) = Bn(i,ng-i+1); Q3(i,ng-i+1) = 255; j4 = fix(m4*i + b4 + 0.5); P4(i,1) = Bn(j4,i); Q4(j4,i) = 255; P5(i,1) = Bn(i,j4); Q5(i,j4) = 255; j7 = fix(-m4*i + b7 + 0.5); P6(i,1) = Bn(i,j7); Q6(i,j7) = 255; P7(i,1) = Bn(j7,i); Q7(j7,i) = 255; end PP = [P0 P1 P2 P3 P4 P5 P6 P7]; d = abs(PP(1,:)-PP(ng,:)); [I,J] = sort(d); Po = PP(:,J(1)); Po = Po/Po(1); m = (Po(ng)-Po(1))/(ng - 1); mb = Po(1)-m; Q = Po-(1:ng)'*m-ones(ng,1)*mb; Qm = mean(Q); Qd = max(Q)-min(Q); Qd1 = log(Qd+1); Qd2 = 2*Qd/(Po(1)+Po(ng)); Qs = std(Q); Qf = fft(Q); Qf = abs(Qf(2:8,1)); if (show) figure(10) clf subplot(2,4,1);plot(PP(:,1));axis([1 ng 0 255]);title('k=4'); subplot(2,4,2);plot(PP(:,2));axis([1 ng 0 255]);title('k=0'); subplot(2,4,3);plot(PP(:,3));axis([1 ng 0 255]);title('k=2'); subplot(2,4,4);plot(PP(:,4));axis([1 ng 0 255]);title('k=6'); subplot(2,4,5);plot(PP(:,5));axis([1 ng 0 255]);title('k=3'); subplot(2,4,6);plot(PP(:,6));axis([1 ng 0 255]);title('k=1'); subplot(2,4,7);plot(PP(:,7));axis([1 ng 0 255]);title('k=7'); subplot(2,4,8);plot(PP(:,8));axis([1 ng 0 255]);title('k=5'); figure(11) clf subplot(2,4,5);plot(PP(:,1));axis([1 ng 0 255]);title('k=4'); subplot(2,4,1);plot(PP(:,2));axis([1 ng 0 255]);title('k=0'); subplot(2,4,3);plot(PP(:,3));axis([1 ng 0 255]);title('k=2'); subplot(2,4,7);plot(PP(:,4));axis([1 ng 0 255]);title('k=6'); subplot(2,4,4);plot(PP(:,5));axis([1 ng 0 255]);title('k=3'); subplot(2,4,2);plot(PP(:,6));axis([1 ng 0 255]);title('k=1'); subplot(2,4,8);plot(PP(:,7));axis([1 ng 0 255]);title('k=7'); subplot(2,4,6);plot(PP(:,8));axis([1 ng 0 255]);title('k=5'); figure(12) imshow([Q0 Q1 Q2 Q3;Q4 Q5 Q6 Q7],gray(256)); figure(13) imshow([Q1 Q5 Q2 Q4;Q0 Q7 Q3 Q6],gray(256)); pause(0); end X = [Qm Qs Qd Qd1 Qd2 Qf']; Xn = [ 'CLP-Qm ' 'CLP-Qs ' 'CLP-Qd ' 'CLP-Qd1 ' 'CLP-Qd2 ' 'CLP-Qf1 ' 'CLP-Qf2 ' 'CLP-Qf3 ' 'CLP-Qf4 ' 'CLP-Qf5 ' 'CLP-Qf6 ' 'CLP-Qf7 '];
github
domingomery/Balu-master
Bfx_lbpi.m
.m
Balu-master/FeatureExtraction/Bfx_lbpi.m
17,985
utf_8
41dcbf073502e4149f5abf197cc3092e
% [X,Xn,options] = Bfx_lbp(I,R,options) % [X,Xn,options] = Bfx_lbp(I,options) % [X,Xn] = Bfx_lbp(I,R,options) % [X,Xn] = Bfx_lbp(I,options) % % Toolbox: Balu % Local Binary Patterns features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % It calculates the LBP over the a regular grid of patches. The function % uses Heikkila & Ahonen (see http://www.cse.oulu.fi/MVG/Research/LBP). % % It returns a matrix of uniform lbp82 descriptors for I, made by % concatenating histograms of each grid cell in the image. % Grid size is options.hdiv * options.vdiv % % R is a binary image or empty. If R is given the lbp will be computed % the corresponding pixles R==0 in image I will be set to 0. % % Output: % X is a matrix of size ((hdiv*vdiv) x 59), each row has a % histogram corresponding to a grid cell. We use 59 bins. % options.x of size hdiv*vdiv is the x coordinates of center of ith grid cell % options.y of size hdiv*vdiv is the y coordinates of center of ith grid cell % Both coordinates are calculated as if image was a square of side length 1. % % References: % Ojala, T.; Pietikainen, M. & Maenpaa, T. Multiresolution gray-scale % and rotation invariant texture classification with local binary % patterns. IEEE Transactions on Pattern Analysis and Machine % Intelligence, 2002, 24, 971-987. % % Mu, Y. et al (2008): Discriminative Local Binary Patterns for Human % Detection in Personal Album. CVPR-2008. % % Example 1: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 0; % classic LBP % options.samples = 8; % number of neighbor samples % options.mappingtype = 'u2'; % uniform LBP % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % LBP features % bar(X) % histogram % % Example 2: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 0; % classic LBP % options.samples = 8; % number of neighbor samples % options.mappingtype = 'ri'; % rotation-invariant LBP % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % LBP features % bar(X) % histogram % % Example 3: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 8; % number of neighbor samples % options.sk = 0.5; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % semantic LBP features % bar(X) % histogram % % Example 4: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 16; % number of neighbor samples % options.sk = 0.5; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % semantic LBP features % bar(X) % histogram % % Example 5: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 8; % number of neighbor samples % options.sk = 0.25; % angle sampling % options.weight = 9; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % weighted LBP features % bar(X) % histogram % See also Bfx_gabor, Bfx_clp, Bfx_fourier, Bfx_dct. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % function [X,Xn,options] = Bfx_lbpi(I,R,options) if nargin==2; options = R; R = ones(size(I)); end if ~isfield(options,'normalize') options.normalize = 0; end % vdiv = options.vdiv; % hdiv = options.hdiv; % % if ~isfield(options,'show') % options.show = 0; % end % % if options.show == 1 % disp('--- extracting local binary patterns features...'); % end % % if ~isfield(options,'samples') % options.samples = 8; % end % % if ~isfield(options,'radius') % options.radius = log(options.samples)/log(2)-1; % end % % if ~isfield(options,'semantic') % options.semantic = 0; % end % % if ~isfield(options,'weight') % options.weight = 0; % end LBPst = 'LBP'; st = 'i'; % if options.semantic>0 % if ~isfield(options,'sk') % options.sk = 1; % end % mapping = getsmapping(options.samples,options.sk); % LBPst = ['s' LBPst]; % st='8x8'; % else % % mapping = getmapping(8,'u2'); % if ~isfield(options,'mappingtype') % options.mappingtype = 'u2'; % end % st = sprintf('%d,%s',options.samples,options.mappingtype); % mapping = getmapping(options.samples,options.mappingtype); % end % get lbp image if ~isempty(R); I(R==0) = 0; end code_img = I; [n1,n2] = size(code_img); % [N,M] = size(I); % Ilbp = zeros(size(I)); % i1 = round((N-n1)/2); % j1 = round((M-n2)/2); % code_img = Ilbp(i1+1:i1+n1,j1+1:j1+n2); % options.Ilbp = Ilbp; %ylen = round(n1/vdiv); %xlen = round(n2/hdiv); % split image into blocks (saved as columns) %grid_img = im2col(code_img,[ylen, xlen], 'distinct'); grid_img = code_img(:); % if options.weight>0 % LBPst = ['w' LBPst]; % mt = 2*options.radius-1; % mt2 = mt^2; % Id = double(I); % switch options.weight % case 1 % W = abs(conv2(Id,ones(mt,mt)/mt2,'same')-Id); % case 2 % W = (abs(conv2(Id,ones(mt,mt)/mt2,'same')-Id))./(Id+1); % case 3 % W = abs(medfilt2(Id,[mt mt])-Id); % case 4 % W = abs(medfilt2(Id,[mt mt])-Id)./(Id+1); % case 5 % W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id); % case 6 % W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id)./(Id+1); % case 7 % Id = conv2(Id,ones(mt,mt)/mt2,'same'); % W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id)./(Id+1); % case 8 % Id = medfilt2(Id,[mt mt]); % W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id)./(Id+1); % case 9 % Id = medfilt2(Id,[mt mt]); % W = abs(ordfilt2(Id,mt2-1,ones(mt,mt))-Id)./(Id+1); % otherwise % error('Bfx_lbp does not recognice options.weight = %d.',options.weight); % end % W = W(mt+1:end-mt,mt+1:end-mt); % grid_W = im2col(W,[ylen, xlen], 'distinct'); % nwi = mapping.num; % nwj = size(grid_W,2); % nwk = size(grid_W,1); % desc = zeros(nwi,nwj); % for j=1:nwj % x = grid_img(:,j)+1; % y = grid_W(:,j); % d = zeros(nwi,1); % for k=1:nwk % d(x(k))=d(x(k))+y(k); % % d(x(k))=d(x(k))+1; % normal LBP each LBP has equal weight % end % desc(:,j) = d; % end % % else desc = hist(double(grid_img), 0:options.maxD-1); % calculate coordinates of descriptors as if I was square w/ side=1 %end %dx = 1.0/hdiv; %dy = 1.0/vdiv; dx = 1; dy = 1; x = dx/2.0: dx :1.0-dx/2.0; y = dy/2.0: dy :1.0-dy/2.0; options.x = x; options.y = y; %if hdiv*vdiv>1 % D = desc'; %else X = desc; if options.normalize X = X/sum(X); end %end [M,N] = size(X); Xn = char(zeros(N*M,24)); % X = zeros(1,N*M); % k=0; % for i=1:M % for j=1:N % k = k+1; % s = sprintf('%s(%d,%d)[%s] ',LBPst,i,j,st); % Xn(k,:) = s(1:24); % X(k) = D(i,j); % end % end end %GETMAPPING returns a structure containing a mapping table for LBP codes. % MAPPING = GETMAPPING(SAMPLES,MAPPINGTYPE) returns a % structure containing a mapping table for % LBP codes in a neighbourhood of SAMPLES sampling % points. Possible values for MAPPINGTYPE are % 'u2' for uniform LBP % 'ri' for rotation-invariant LBP % 'riu2' for uniform rotation-invariant LBP. % % Example: % I=imread('rice.tif'); % MAPPING=getmapping(16,'riu2'); % LBPHIST=lbp(I,2,16,MAPPING,'hist'); % Now LBPHIST contains a rotation-invariant uniform LBP % histogram in a (16,2) neighbourhood. % function mapping = getmapping(samples,mappingtype) % Version 0.1.1 % Authors: Marko Heikkila and Timo Ahonen % Changelog % 0.1.1 Changed output to be a structure % Fixed a bug causing out of memory errors when generating rotation % invariant mappings with high number of sampling points. % Lauge Sorensen is acknowledged for spotting this problem. table = 0:2^samples-1; newMax = 0; %number of patterns in the resulting LBP code index = 0; if strcmp(mappingtype,'u2') %Uniform 2 newMax = samples*(samples-1) + 3; for i = 0:2^samples-1 j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate left numt = sum(bitget(bitxor(i,j),1:samples)); %number of 1->0 and %0->1 transitions %in binary string %x is equal to the %number of 1-bits in %XOR(x,Rotate left(x)) if numt <= 2 table(i+1) = index; index = index + 1; else table(i+1) = newMax - 1; end end end if strcmp(mappingtype,'ri') %Rotation invariant tmpMap = zeros(2^samples,1) - 1; for i = 0:2^samples-1 rm = i; r = i; for j = 1:samples-1 r = bitset(bitshift(r,1,samples),1,bitget(r,samples)); %rotate %left if r < rm rm = r; end end if tmpMap(rm+1) < 0 tmpMap(rm+1) = newMax; newMax = newMax + 1; end table(i+1) = tmpMap(rm+1); end end if strcmp(mappingtype,'riu2') %Uniform & Rotation invariant newMax = samples + 2; for i = 0:2^samples - 1 j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate left numt = sum(bitget(bitxor(i,j),1:samples)); if numt <= 2 table(i+1) = sum(bitget(i,1:samples)); else table(i+1) = samples+1; end end end mapping.table=table; mapping.samples=samples; mapping.num=newMax; end % LBP returns the local binary pattern image or LBP histogram of an image. % J = LBP(I,R,N,MAPPING,MODE) returns either a local binary pattern % coded image or the local binary pattern histogram of an intensity % image I. The LBP codes are computed using N sampling points on a % circle of radius R and using mapping table defined by MAPPING. % See the getmapping function for different mappings and use 0 for % no mapping. Possible values for MODE are % 'h' or 'hist' to get a histogram of LBP codes % 'nh' to get a normalized histogram % Otherwise an LBP code image is returned. % % J = LBP(I) returns the original (basic) LBP histogram of image I % % J = LBP(I,SP,MAPPING,MODE) computes the LBP codes using n sampling % points defined in (n * 2) matrix SP. The sampling points should be % defined around the origin (coordinates (0,0)). % % Examples % -------- % I=imread('rice.png'); % mapping=getmapping(8,'u2'); % H1=LBP(I,1,8,mapping,'h'); %LBP histogram in (8,1) neighborhood % %using uniform patterns % subplot(2,1,1),stem(H1); % % H2=LBP(I); % subplot(2,1,2),stem(H2); % % SP=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1]; % I2=LBP(I,SP,0,'i'); %LBP code image using sampling points in SP % %and no mapping. Now H2 is equal to histogram % %of I2. function result = lbp(varargin) % image,radius,neighbors,mapping,mode) % Version 0.3.2 % Authors: Marko Heikkila and Timo Ahonen % Changelog % Version 0.3.2: A bug fix to enable using mappings together with a % predefined spoints array % Version 0.3.1: Changed MAPPING input to be a struct containing the mapping % table and the number of bins to make the function run faster with high number % of sampling points. Lauge Sorensen is acknowledged for spotting this problem. % Check number of input arguments. error(nargchk(1,5,nargin)); image=varargin{1}; d_image=double(image); if nargin==1 spoints=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1]; neighbors=8; mapping=0; mode='h'; end if (nargin == 2) && (length(varargin{2}) == 1) error('Input arguments'); end if (nargin > 2) && (length(varargin{2}) == 1) radius=varargin{2}; neighbors=varargin{3}; spoints=zeros(neighbors,2); % Angle step. a = 2*pi/neighbors; for i = 1:neighbors spoints(i,1) = -radius*sin((i-1)*a); spoints(i,2) = radius*cos((i-1)*a); end if(nargin >= 4) mapping=varargin{4}; if(isstruct(mapping) && mapping.samples ~= neighbors) error('Incompatible mapping'); end else mapping=0; end if(nargin >= 5) mode=varargin{5}; else mode='h'; end end if (nargin > 1) && (length(varargin{2}) > 1) spoints=varargin{2}; neighbors=size(spoints,1); if(nargin >= 3) mapping=varargin{3}; if(isstruct(mapping) && mapping.samples ~= neighbors) error('Incompatible mapping'); end else mapping=0; end if(nargin >= 4) mode=varargin{4}; else mode='h'; end end % Determine the dimensions of the input image. [ysize xsize] = size(image); miny=min(spoints(:,1)); maxy=max(spoints(:,1)); minx=min(spoints(:,2)); maxx=max(spoints(:,2)); % Block size, each LBP code is computed within a block of size bsizey*bsizex bsizey=ceil(max(maxy,0))-floor(min(miny,0))+1; bsizex=ceil(max(maxx,0))-floor(min(minx,0))+1; % Coordinates of origin (0,0) in the block origy=1-floor(min(miny,0)); origx=1-floor(min(minx,0)); % Minimum allowed size for the input image depends % on the radius of the used LBP operator. if(xsize < bsizex || ysize < bsizey) error('Too small input image. Should be at least (2*radius+1) x (2*radius+1)'); end % Calculate dx and dy; dx = xsize - bsizex; dy = ysize - bsizey; % Fill the center pixel matrix C. C = image(origy:origy+dy,origx:origx+dx); d_C = double(C); bins = 2^neighbors; % Initialize the result matrix with zeros. result=zeros(dy+1,dx+1); %Compute the LBP code image for i = 1:neighbors y = spoints(i,1)+origy; x = spoints(i,2)+origx; % Calculate floors, ceils and rounds for the x and y. fy = floor(y); cy = ceil(y); ry = round(y); fx = floor(x); cx = ceil(x); rx = round(x); % Check if interpolation is needed. if (abs(x - rx) < 1e-6) && (abs(y - ry) < 1e-6) % Interpolation is not needed, use original datatypes N = image(ry:ry+dy,rx:rx+dx); D = N >= C; else % Interpolation needed, use double type images ty = y - fy; tx = x - fx; % Calculate the interpolation weights. w1 = (1 - tx) * (1 - ty); w2 = tx * (1 - ty); w3 = (1 - tx) * ty ; w4 = tx * ty ; % Compute interpolated pixel values N = w1*d_image(fy:fy+dy,fx:fx+dx) + w2*d_image(fy:fy+dy,cx:cx+dx) + ... w3*d_image(cy:cy+dy,fx:fx+dx) + w4*d_image(cy:cy+dy,cx:cx+dx); D = N >= d_C; end % Update the result matrix. v = 2^(i-1); result = result + v*D; end %Apply mapping if it is defined if isstruct(mapping) bins = mapping.num; for i = 1:size(result,1) for j = 1:size(result,2) result(i,j) = mapping.table(result(i,j)+1); end end end if (strcmp(mode,'h') || strcmp(mode,'hist') || strcmp(mode,'nh')) % Return with LBP histogram if mode equals 'hist'. result=hist(result(:),0:(bins-1)); if (strcmp(mode,'nh')) result=result/sum(result); end else %Otherwise return a matrix of unsigned integers if ((bins-1)<=intmax('uint8')) result=uint8(result); elseif ((bins-1)<=intmax('uint16')) result=uint16(result); else result=uint32(result); end end end % Mapping for sLBB function mapping = getsmapping(N,sk) M = 2^N; samples = N; len = zeros(M,1); ang = zeros(M,1); for x=0:(M-1) k = x+1; j = bitset(bitshift(x,1,samples),1,bitget(x,samples)); numt = sum(bitget(bitxor(x,j),1:samples)); c = numt; if c>2 len(k)=-1; ang(k)=-1; else s = bitget(x,1:samples); len(k) = sum(s); if c==0 ang(k)=0; else r = 0; while (s(1)~=0) || (s(N)~=1) s = [s(2:N) s(1)]; r = r+1; end ii = find(s==1); a = mean(ii)+r; if a>N a=a-N; end ang(k) = round(sk*a)-1; end end % fprintf('%4d: %s (%d,%d)\n',x,dec2bin(x,N),len(k),ang(k)); pause end Ma = max(ang)+1; map = len*Ma+ang-Ma+1; n = max(map)+1; map(ang==-1) = n; map(1) = 0; mapping.table = map'; mapping.samples = N; mapping.num = n+1; end
github
domingomery/Balu-master
Bfx_lbp_old.m
.m
Balu-master/FeatureExtraction/Bfx_lbp_old.m
18,020
utf_8
5d0a1fbb2228d5669c26283336b539fe
% [X,Xn,options] = Bfx_lbp(I,R,options) % [X,Xn,options] = Bfx_lbp(I,options) % [X,Xn] = Bfx_lbp(I,R,options) % [X,Xn] = Bfx_lbp(I,options) % % Toolbox: Balu % Local Binary Patterns features % % X is the features vector, Xn is the list of feature names (see Example % to see how it works). % % It calculates the LBP over the a regular grid of patches. The function % uses Heikkila & Ahonen (see http://www.cse.oulu.fi/MVG/Research/LBP). % % It returns a matrix of uniform lbp82 descriptors for I, made by % concatenating histograms of each grid cell in the image. % Grid size is options.hdiv * options.vdiv % % R is a binary image or empty. If R is given the lbp will be computed % the corresponding pixles R==0 in image I will be set to 0. % % Output: % X is a matrix of size ((hdiv*vdiv) x 59), each row has a % histogram corresponding to a grid cell. We use 59 bins. % options.x of size hdiv*vdiv is the x coordinates of center of ith grid cell % options.y of size hdiv*vdiv is the y coordinates of center of ith grid cell % Both coordinates are calculated as if image was a square of side length 1. % % References: % Ojala, T.; Pietikainen, M. & Maenpaa, T. Multiresolution gray-scale % and rotation invariant texture classification with local binary % patterns. IEEE Transactions on Pattern Analysis and Machine % Intelligence, 2002, 24, 971-987. % % Mu, Y. et al (2008): Discriminative Local Binary Patterns for Human % Detection in Personal Album. CVPR-2008. % % Example 1: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 0; % classic LBP % options.samples = 8; % number of neighbor samples % options.mappingtype = 'u2'; % uniform LBP % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % figure(1);imshow(J,[]) % image to be analyzed % [X,Xn] = Bfx_lbp(J,[],options); % LBP features % figure(2);bar(X) % histogram % % Example 2: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 0; % classic LBP % options.samples = 8; % number of neighbor samples % options.mappingtype = 'ri'; % rotation-invariant LBP % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % figure(1);imshow(J,[]) % image to be analyzed % [X,Xn] = Bfx_lbp(J,[],options); % LBP features % bar(X) % histogram % % Example 3: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 8; % number of neighbor samples % options.sk = 0.5; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % semantic LBP features % bar(X) % histogram % % Example 4: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 16; % number of neighbor samples % options.sk = 0.5; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % semantic LBP features % bar(X) % histogram % % Example 5: % options.vdiv = 1; % one vertical divition % options.hdiv = 1; % one horizontal divition % options.semantic = 1; % semantic LBP % options.samples = 8; % number of neighbor samples % options.sk = 0.25; % angle sampling % options.weight = 9; % angle sampling % I = imread('testimg1.jpg'); % input image % J = I(120:219,120:239,2); % region of interest (green) % [X,Xn] = Bfx_lbp(J,[],options); % weighted LBP features % bar(X) % histogram % See also Bfx_gabor, Bfx_clp, Bfx_fourier, Bfx_dct. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl % function [X,Xn,options] = Bfx_lbp(I,R,options) if nargin==2; options = R; R = ones(size(I)); end vdiv = options.vdiv; hdiv = options.hdiv; if ~isfield(options,'show') options.show = 0; end if ~isfield(options,'normalize') options.normalize = 0; end if options.show == 1 disp('--- extracting local binary patterns features...'); end if ~isfield(options,'samples') options.samples = 8; end if ~isfield(options,'integral') options.integral = 0; end if ~isfield(options,'radius') options.radius = log(options.samples)/log(2)-1; end if ~isfield(options,'semantic') options.semantic = 0; end if ~isfield(options,'weight') options.weight = 0; end LBPst = 'LBP'; if options.semantic>0 if ~isfield(options,'sk') options.sk = 1; end mapping = getsmapping(options.samples,options.sk); LBPst = ['s' LBPst]; st='8x8'; else % mapping = getmapping(8,'u2'); if ~isfield(options,'mappingtype') options.mappingtype = 'u2'; end st = sprintf('%d,%s',options.samples,options.mappingtype); mapping = getmapping(options.samples,options.mappingtype); end % get lbp image if ~isempty(R); I(R==0) = 0; end code_img = lbp(I,options.radius,options.samples,mapping,''); [n1,n2] = size(code_img); [N,M] = size(I); Ilbp = zeros(size(I)); i1 = round((N-n1)/2); j1 = round((M-n2)/2); Ilbp(i1+1:i1+n1,j1+1:j1+n2) = code_img; options.Ilbp = Ilbp; if options.integral == 1 options.Hx = Bim_inthist(Ilbp+1,options.maxD); end ylen = round(n1/vdiv); xlen = round(n2/hdiv); % split image into blocks (saved as columns) grid_img = im2col(code_img,[ylen, xlen], 'distinct'); if options.weight>0 LBPst = ['w' LBPst]; mt = 2*options.radius-1; mt2 = mt^2; Id = double(I); switch options.weight case 1 W = abs(conv2(Id,ones(mt,mt)/mt2,'same')-Id); case 2 W = (abs(conv2(Id,ones(mt,mt)/mt2,'same')-Id))./(Id+1); case 3 W = abs(medfilt2(Id,[mt mt])-Id); case 4 W = abs(medfilt2(Id,[mt mt])-Id)./(Id+1); case 5 W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id); case 6 W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id)./(Id+1); case 7 Id = conv2(Id,ones(mt,mt)/mt2,'same'); W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id)./(Id+1); case 8 Id = medfilt2(Id,[mt mt]); W = abs(ordfilt2(Id,mt2,ones(mt,mt))-Id)./(Id+1); case 9 Id = medfilt2(Id,[mt mt]); W = abs(ordfilt2(Id,mt2-1,ones(mt,mt))-Id)./(Id+1); otherwise error('Bfx_lbp does not recognice options.weight = %d.',options.weight); end W = W(mt+1:end-mt,mt+1:end-mt); grid_W = im2col(W,[ylen, xlen], 'distinct'); nwi = mapping.num; nwj = size(grid_W,2); nwk = size(grid_W,1); desc = zeros(nwi,nwj); for j=1:nwj x = grid_img(:,j)+1; y = grid_W(:,j); d = zeros(nwi,1); for k=1:nwk d(x(k))=d(x(k))+y(k); % d(x(k))=d(x(k))+1; % normal LBP each LBP has equal weight end desc(:,j) = d; end else desc = hist(double(grid_img), 0:mapping.num-1); % calculate coordinates of descriptors as if I was square w/ side=1 end dx = 1.0/hdiv; dy = 1.0/vdiv; x = dx/2.0: dx :1.0-dx/2.0; y = dy/2.0: dy :1.0-dy/2.0; options.x = x; options.y = y; if hdiv*vdiv>1 D = desc'; else D = desc; end [M,N] = size(D); Xn = char(zeros(N*M,24)); X = zeros(1,N*M); k=0; for i=1:M for j=1:N k = k+1; s = sprintf('%s(%d,%d)[%s] ',LBPst,i,j,st); Xn(k,:) = s(1:24); X(k) = D(i,j); end end if options.normalize X = X/sum(X); end end %GETMAPPING returns a structure containing a mapping table for LBP codes. % MAPPING = GETMAPPING(SAMPLES,MAPPINGTYPE) returns a % structure containing a mapping table for % LBP codes in a neighbourhood of SAMPLES sampling % points. Possible values for MAPPINGTYPE are % 'u2' for uniform LBP % 'ri' for rotation-invariant LBP % 'riu2' for uniform rotation-invariant LBP. % % Example: % I=imread('rice.tif'); % MAPPING=getmapping(16,'riu2'); % LBPHIST=lbp(I,2,16,MAPPING,'hist'); % Now LBPHIST contains a rotation-invariant uniform LBP % histogram in a (16,2) neighbourhood. % function mapping = getmapping(samples,mappingtype) % Version 0.1.1 % Authors: Marko Heikkila and Timo Ahonen % Changelog % 0.1.1 Changed output to be a structure % Fixed a bug causing out of memory errors when generating rotation % invariant mappings with high number of sampling points. % Lauge Sorensen is acknowledged for spotting this problem. table = 0:2^samples-1; newMax = 0; %number of patterns in the resulting LBP code index = 0; if strcmp(mappingtype,'u2') %Uniform 2 newMax = samples*(samples-1) + 3; for i = 0:2^samples-1 j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate left numt = sum(bitget(bitxor(i,j),1:samples)); %number of 1->0 and %0->1 transitions %in binary string %x is equal to the %number of 1-bits in %XOR(x,Rotate left(x)) if numt <= 2 table(i+1) = index; index = index + 1; else table(i+1) = newMax - 1; end end end if strcmp(mappingtype,'ri') %Rotation invariant tmpMap = zeros(2^samples,1) - 1; for i = 0:2^samples-1 rm = i; r = i; for j = 1:samples-1 r = bitset(bitshift(r,1,samples),1,bitget(r,samples)); %rotate %left if r < rm rm = r; end end if tmpMap(rm+1) < 0 tmpMap(rm+1) = newMax; newMax = newMax + 1; end table(i+1) = tmpMap(rm+1); end end if strcmp(mappingtype,'riu2') %Uniform & Rotation invariant newMax = samples + 2; for i = 0:2^samples - 1 j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate left numt = sum(bitget(bitxor(i,j),1:samples)); if numt <= 2 table(i+1) = sum(bitget(i,1:samples)); else table(i+1) = samples+1; end end end mapping.table=table; mapping.samples=samples; mapping.num=newMax; end % LBP returns the local binary pattern image or LBP histogram of an image. % J = LBP(I,R,N,MAPPING,MODE) returns either a local binary pattern % coded image or the local binary pattern histogram of an intensity % image I. The LBP codes are computed using N sampling points on a % circle of radius R and using mapping table defined by MAPPING. % See the getmapping function for different mappings and use 0 for % no mapping. Possible values for MODE are % 'h' or 'hist' to get a histogram of LBP codes % 'nh' to get a normalized histogram % Otherwise an LBP code image is returned. % % J = LBP(I) returns the original (basic) LBP histogram of image I % % J = LBP(I,SP,MAPPING,MODE) computes the LBP codes using n sampling % points defined in (n * 2) matrix SP. The sampling points should be % defined around the origin (coordinates (0,0)). % % Examples % -------- % I=imread('rice.png'); % mapping=getmapping(8,'u2'); % H1=LBP(I,1,8,mapping,'h'); %LBP histogram in (8,1) neighborhood % %using uniform patterns % subplot(2,1,1),stem(H1); % % H2=LBP(I); % subplot(2,1,2),stem(H2); % % SP=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1]; % I2=LBP(I,SP,0,'i'); %LBP code image using sampling points in SP % %and no mapping. Now H2 is equal to histogram % %of I2. function result = lbp(varargin) % image,radius,neighbors,mapping,mode) % Version 0.3.2 % Authors: Marko Heikkila and Timo Ahonen % Changelog % Version 0.3.2: A bug fix to enable using mappings together with a % predefined spoints array % Version 0.3.1: Changed MAPPING input to be a struct containing the mapping % table and the number of bins to make the function run faster with high number % of sampling points. Lauge Sorensen is acknowledged for spotting this problem. % Check number of input arguments. error(nargchk(1,5,nargin)); image=varargin{1}; d_image=double(image); if nargin==1 spoints=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1]; neighbors=8; mapping=0; mode='h'; end if (nargin == 2) && (length(varargin{2}) == 1) error('Input arguments'); end if (nargin > 2) && (length(varargin{2}) == 1) radius=varargin{2}; neighbors=varargin{3}; spoints=zeros(neighbors,2); % Angle step. a = 2*pi/neighbors; for i = 1:neighbors spoints(i,1) = -radius*sin((i-1)*a); spoints(i,2) = radius*cos((i-1)*a); end if(nargin >= 4) mapping=varargin{4}; if(isstruct(mapping) && mapping.samples ~= neighbors) error('Incompatible mapping'); end else mapping=0; end if(nargin >= 5) mode=varargin{5}; else mode='h'; end end if (nargin > 1) && (length(varargin{2}) > 1) spoints=varargin{2}; neighbors=size(spoints,1); if(nargin >= 3) mapping=varargin{3}; if(isstruct(mapping) && mapping.samples ~= neighbors) error('Incompatible mapping'); end else mapping=0; end if(nargin >= 4) mode=varargin{4}; else mode='h'; end end % Determine the dimensions of the input image. [ysize xsize] = size(image); miny=min(spoints(:,1)); maxy=max(spoints(:,1)); minx=min(spoints(:,2)); maxx=max(spoints(:,2)); % Block size, each LBP code is computed within a block of size bsizey*bsizex bsizey=ceil(max(maxy,0))-floor(min(miny,0))+1; bsizex=ceil(max(maxx,0))-floor(min(minx,0))+1; % Coordinates of origin (0,0) in the block origy=1-floor(min(miny,0)); origx=1-floor(min(minx,0)); % Minimum allowed size for the input image depends % on the radius of the used LBP operator. if(xsize < bsizex || ysize < bsizey) error('Too small input image. Should be at least (2*radius+1) x (2*radius+1)'); end % Calculate dx and dy; dx = xsize - bsizex; dy = ysize - bsizey; % Fill the center pixel matrix C. C = image(origy:origy+dy,origx:origx+dx); d_C = double(C); bins = 2^neighbors; % Initialize the result matrix with zeros. result=zeros(dy+1,dx+1); %Compute the LBP code image for i = 1:neighbors y = spoints(i,1)+origy; x = spoints(i,2)+origx; % Calculate floors, ceils and rounds for the x and y. fy = floor(y); cy = ceil(y); ry = round(y); fx = floor(x); cx = ceil(x); rx = round(x); % Check if interpolation is needed. if (abs(x - rx) < 1e-6) && (abs(y - ry) < 1e-6) % Interpolation is not needed, use original datatypes N = image(ry:ry+dy,rx:rx+dx); D = N >= C; else % Interpolation needed, use double type images ty = y - fy; tx = x - fx; % Calculate the interpolation weights. w1 = (1 - tx) * (1 - ty); w2 = tx * (1 - ty); w3 = (1 - tx) * ty ; w4 = tx * ty ; % Compute interpolated pixel values N = w1*d_image(fy:fy+dy,fx:fx+dx) + w2*d_image(fy:fy+dy,cx:cx+dx) + ... w3*d_image(cy:cy+dy,fx:fx+dx) + w4*d_image(cy:cy+dy,cx:cx+dx); D = N >= d_C; end % Update the result matrix. v = 2^(i-1); result = result + v*D; end %Apply mapping if it is defined if isstruct(mapping) bins = mapping.num; for i = 1:size(result,1) for j = 1:size(result,2) result(i,j) = mapping.table(result(i,j)+1); end end end if (strcmp(mode,'h') || strcmp(mode,'hist') || strcmp(mode,'nh')) % Return with LBP histogram if mode equals 'hist'. result=hist(result(:),0:(bins-1)); if (strcmp(mode,'nh')) result=result/sum(result); end else %Otherwise return a matrix of unsigned integers if ((bins-1)<=intmax('uint8')) result=uint8(result); elseif ((bins-1)<=intmax('uint16')) result=uint16(result); else result=uint32(result); end end end % Mapping for sLBB function mapping = getsmapping(N,sk) M = 2^N; samples = N; len = zeros(M,1); ang = zeros(M,1); for x=0:(M-1) k = x+1; j = bitset(bitshift(x,1,samples),1,bitget(x,samples)); numt = sum(bitget(bitxor(x,j),1:samples)); c = numt; if c>2 len(k)=-1; ang(k)=-1; else s = bitget(x,1:samples); len(k) = sum(s); if c==0 ang(k)=0; else r = 0; while (s(1)~=0) || (s(N)~=1) s = [s(2:N) s(1)]; r = r+1; end ii = find(s==1); a = mean(ii)+r; if a>N a=a-N; end ang(k) = round(sk*a)-1; end end % fprintf('%4d: %s (%d,%d)\n',x,dec2bin(x,N),len(k),ang(k)); pause end Ma = max(ang)+1; map = len*Ma+ang-Ma+1; n = max(map)+1; map(ang==-1) = n; map(1) = 0; mapping.table = map'; mapping.samples = N; mapping.num = n+1; end
github
domingomery/Balu-master
Bfx_geo.m
.m
Balu-master/FeatureExtraction/Bfx_geo.m
2,922
utf_8
446405d4d737c6637957ae9496e02e5a
% [X,Xn] = Bfx_geo(R,options) % [X,Xn] = Bfx_geo(L,options) % % Toolbox: Balu % % Gemteric feature extraction. % % This function calls gemetric feature extraction procedures of binary % image R or labelled image L. % % X is the feature matrix (one feature per column, one sample per row), % Xn is the list with the names of these features (see Example % to see how it works). % % Example 1: Extraction of one region image % b(1).name = 'hugeo'; b(1).options.show=1; % Hu moments % b(2).name = 'flusser'; b(2).options.show=1; % Flusser moments % b(3).name = 'fourierdes'; b(3).options.show=1; % Fourier % b(3).options.Nfourierdes=12; % descriptors % options.b = b; % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % [X,Xn] = Bfx_geo(R,options); % geometric features % Bio_printfeatures(X,Xn) % % Example 2: Extraction of multiple regions image % b(1).name = 'hugeo'; b(1).options.show=1; % Hu moments % b(2).name = 'basicgeo'; b(2).options.show=1; % basic geometric fetaures % b(3).name = 'fourierdes'; b(3).options.show=1; % Fourier % b(3).options.Nfourierdes=12; % descriptors % options.b = b; % I = imread('rice.png'); % input image % [R,m] = Bim_segmowgli(I,ones(size(I)),40,1.5); % segmentation % [X,Xn] = Bfx_geo(R,options); % geometric features % figure; hist(X(:,12));xlabel([Xn(12,:)]) % area histogramm % ii = find(abs(X(:,20))<15); % rice orientation % K = zeros(size(R)); % between -15 and 15 grad % for i=1:length(ii);K=or(K,R==ii(i));end % figure; imshow(K);title('abs(orientation)<15 grad') % % See also Bfx_basicgeo, Bfx_hugeo, Bfx_flusser, Bfx_gupta, % Bfx_fitellipse, Bfx_fourierdes, Bfx_files. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_geo(R,options) if isempty(R) error('Bfx_geo: R is empty. Geometric features without segmentation has no sense.'); else b = options.b; n = length(b); m = int16(max(R(:))); X = []; for j=1:m Rj = R==j; Xj = []; Xnj = []; for i=1:n s = b(i).name; if sum(s(1:3)=='Bfx')~=3 s = ['Bfx_' s]; end if ~exist(s,'file') error(sprintf('Bfx_geo: function %s does not exist.',b(i).name)) end [Xi,Xni] = feval(s,Rj,b(i).options); Xj = [Xj Xi]; Xnj = [Xnj; Xni]; end X = [X;Xj]; end Xn = Xnj; end
github
domingomery/Balu-master
Bfx_int.m
.m
Balu-master/FeatureExtraction/Bfx_int.m
5,881
utf_8
580daf50396b7da9cbd6894e5fc8da80
% [X,Xn] = Bfx_int(I,R,b) % % Toolbox: Balu % % Intensity feature extraction. % % This function calls intensity feature extraction procedures of image I % according binary image R. See example to see how it works. % % X is the feature matrix (one feature per column, one sample per row), % Xn is the list of feature names (see Examples to see how it works). % % Example 1: Extraction of one region image in grayvalue images % b(1).name = 'gabor'; b(1).options.show=1; % Gabor features % b(1).options.Lgabor = 8; % number of rotations % b(1).options.Sgabor = 8; % number of dilations (scale) % b(1).options.fhgabor = 2; % highest frequency of interest % b(1).options.flgabor = 0.1; % lowest frequency of interest % b(1).options.Mgabor = 21; % mask size % b(2).name = 'basicint'; b(2).options.show=1; % Basic intensity features % b(3).name = 'lbp'; b(3).options.show=1; % LBP % b(3).options.vdiv = 2; % vertical div % b(3).options.hdiv = 2; % horizontal div % options.b = b; % options.colstr = 'i'; % gray image % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % J = rgb2gray(I); % grayvalue image % [X,Xn] = Bfx_int(J,R,options); % intensity features % Bio_printfeatures(X,Xn) % % Example 2: Extraction of multiple regions image % b(1).name = 'huint'; b(1).options.show=1; % Hu moments % b(2).name = 'basicint'; b(2).options.show=1; % Basic intensity features % b(3).name = 'lbp'; b(3).options.show=1; % LBP % b(3).options.vdiv = 2; % vertical div % b(3).options.hdiv = 2; % horizontal div % b(4).name = 'contrast'; b(4).options.show = 1; % Contrast % b(4).options.neighbor = 1; % neighborhood is a window % b(4).options.param = 1.5; % 1.5 height x 1.5 width % I = imread('rice.png'); % input image % [R,m] = Bim_segmowgli(I,ones(size(I)),40,1.5); % segmentation % options.b = b; % options.colstr = 'i'; % gray image % [X,Xn] = Bfx_int(I,R,options); % intensity features % figure; hist(X(:,9));xlabel([Xn(9,:)]) % std dev histogramm % figure; hist(X(:,253));xlabel([Xn(253,:)]) % contrast Ks histogramm % % Example 3: Extraction of one region image in RGB images % b(1).name = 'gabor'; b(1).options.show=1; % Gabor features % b(1).options.Lgabor = 8; % number of rotations % b(1).options.Sgabor = 8; % number of dilations (scale) % b(1).options.fhgabor = 2; % highest frequency of interest % b(1).options.flgabor = 0.1; % lowest frequency of interest % b(1).options.Mgabor = 21; % mask size % b(2).name = 'basicint'; b(2).options.show=1; % Basic intensity features % b(3).name = 'lbp'; b(3).options.show=1; % LBP % b(3).options.vdiv = 2; % vertical div % b(3).options.hdiv = 2; % horizontal div % options.b = b; % options.colstr = 'rgb'; % R image % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % [X,Xn] = Bfx_int(I,R,options); % intensity features % Bio_printfeatures(X,Xn) % % See also Bfx_basicint, Bfx_haralick, Bfx_gabor, Bfx_dct, Bfx_fourier, % Bfx_huint, Bfx_lbp, Bfx_contrast, Bfx_clp, Bfx_phog, % Bfx_files. % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_int(I,R,options) I = double(I); [N,M,P] = size(I); c = size(I,3); if nargin==2; options = R; R = ones(size(I)); end if isempty(R) R = ones(N,M); end b = options.b; colstr = options.colstr; n = length(b); m = int16(max(R(:))); X = []; Xn = []; for j=1:m Rj = R==j; Xj = []; if j==1 Xn = []; end for i=1:n s = b(i).name; if sum(s(1:2)=='Bf')~=2 s = ['Bfx_' s]; end if ~exist(s,'file') error(sprintf('Bfx_extraction: function %s does not exist.',b(i).name)) end % if or(compare(s,'Bfx_lbphogi')==0,compare(s,'Bfx_hogi')==0) % if (compare(s(1:8),'Bfx_lbpi')*compare(s,'Bfx_lbphogi')*compare(s,'Bfx_hogi'))==0 if (compare(s,'Bfx_lbpi')*compare(s,'Bfx_lbphogi')*compare(s,'Bfx_hogi'))==0 c = 1; ifull = 1; else c = P; ifull = 0; end for k=1:c % for i=1:n if ifull % tic [Xk,Xnk] = feval(s,I,Rj,b(i).options); % toc else [Xk,Xnk] = feval(s,I(:,:,k),Rj,b(i).options); end Xj = [Xj Xk]; if j==1 nk = length(Xk); Xns = [ones(nk,1)*[colstr(k) '-'] Xnk ]; Xn = [Xn; Xns(:,1:24)]; end end end X = [X;Xj]; end
github
domingomery/Balu-master
Bfx_all.m
.m
Balu-master/FeatureExtraction/Bfx_all.m
499
utf_8
dd2f13d940eb76ecc4bb1cbf3cea7857
% [X,Xn] = Bfx_all(I,R,options) % [X,Xn] = Bfx_all(I,options) % % Toolbox: Balu % All pixels. % % X is the features vector, Xn is the list feature names (see Example to % see how it works). % % % Example: % I = imread('testimg1.jpg'); % input image % [X,Xn] = Bfx_all(I); % all pixels % % % (c) D.Mery, PUC-DCC, 2012 % http://dmery.ing.puc.cl function [X,Xn] = Bfx_all(I,R,options) X = I(:)'; Xn = zeros(length(X),24);
github
domingomery/Balu-master
num2fixstr.m
.m
Balu-master/Miscellaneous/num2fixstr.m
347
utf_8
842ba059f8799b2c4a46e890de6cee74
%function st = num2fixstr(i,d) % % This function converts an integer i in a string % st with a fixed number of characters (with '0' % filled from left. % % Example: % st = num2fixstr(3,4) % returns '0003' % % D.Mery, Aug-2012 % http://dmery.ing.puc.cl % function st = num2fixstr(i,d) s = [char('0'*ones(1,d)) num2str(i)]; st = s(end-d+1:end);
github
domingomery/Balu-master
enterpause.m
.m
Balu-master/Miscellaneous/enterpause.m
311
utf_8
a24fcf539906b8dc95c0e17d240bd116
% Toolbox: Balu % enterpause display "press <Enter> to continue..." and wait for <Enter> % enterpause(t) means pause(t) % % D.Mery, PUC-DCC, Apr. 2008 % http://dmery.ing.puc.cl function enterpause(t) if ~exist('t','var') disp('press <Enter> to continue...') pause else pause(t) end
github
domingomery/Balu-master
posrandom.m
.m
Balu-master/Miscellaneous/posrandom.m
279
utf_8
e209ba3e41ac82dd560a8ff602aad8af
% It changes the order of the columns or rows of x randomly. Variable dim % selects the dimension along which to change. function [x_new,j] = posrandom(x,dim) nx = size(x,dim); r = rand(nx,1); [i,j] = sort(r); if dim==1 x_new = x(j,:); else x_new = x(:,j); end
github
domingomery/Balu-master
cart2polpos.m
.m
Balu-master/Miscellaneous/cart2polpos.m
870
utf_8
b291b2687cca1f26635f22687f1ebc7b
% [t,r] = cart2polpos(x,y,s) % % Toolbox: Balu % transform Cartesian to polar coordinates. The angle t will be always % positive. If s==0, the t is between 0 and 2*pi. If s > 0, the angles are % subdivided into s bins, and t means in which bin the angle is located. % % Examples: % [t,r] = cart2polpos(1,1) % it is the same as [t,r] = cart2polpos(1,1,0) % the result for t is pi/4 and for r = sqrt(2)/2 % % [t,r] = cart2polpos(1,-1) % it is the same as [t,r] = cart2polpos(1,1,0) % the result for t is 7*pi/4 and for r = sqrt(2)/2 % % [t,r] = cart2polpos(1,-1,4) % example that computes the quadrant % the result for t is 4 and for r = sqrt(2)/2 % % D.Mery, PUC-DCC, 2014 % http://dmery.ing.puc.cl function [t,r] = cart2polpos(x,y,s) if ~exist('s','var') s=0; end [t,r] = cart2pol(x,y); t(t<0) = t(t<0)+2*pi; if s>0 t = fix(t/2/pi*s)+1; end
github
domingomery/Balu-master
distxy.m
.m
Balu-master/Miscellaneous/distxy.m
2,111
utf_8
549e0d02ce5a7c63b7150ee7d5e67ab1
% function D = distxy(x,y,method) % % Toolbox: Balu % % It computes distances of each row of x with each row of y % x is a Nx x n matrix, y is a Ny x n matrix % D is a Nx x Ny matrix, where D(i,j) = norm(x(i,:)-y(j,:)); % method = 1: it computes row per row % 2: it computes each row of x with all rows of y % 3: it computes all rows of x with all rows of y % method 3 is faster than method 2, and this faster than method 1 % method 3 requires more memory than method 2, and this more than method 1 % method 3 is the default. % % Example: % x = rand(100,7); % y = rand(100,7); % D = distxy(x,y); % default is method 3 % % D.Mery, PUC-DCC, 2012 % http://dmery.ing.puc.cl function D = distxy(x,y,method) if ~exist('method','var') method = 3; end [Nx,nx] = size(x); [Ny,ny] = size(y); if nx~=ny error('number of elements of columns of x and y must be same...') end n = nx; D = zeros(Nx,Ny); switch method case 1 % ff = Bio_statusbar('distances'); for i=1:Nx % Bio_statusbar(i/Nx,ff); for j=1:Ny D(i,j) = norm(x(i,:)-y(j,:)); end end % delete(ff) case 2 % ff = Bio_statusbar('distances'); for i=1:Nx % Bio_statusbar(i/Nx,ff); di = ones(Ny,1)*x(i,:)-y; D(i,:) = sqrt(sum(di.*di,2)'); end % delete(ff) case 3 xs = zeros(1,n,Nx); xs(:) = x'; Sx = repmat(xs,[Ny 1 1]); Sx = Sx-repmat(y,[1 1 Nx]); Sx = Sx.*Sx; R = sqrt(sum(Sx,2)); Dr = zeros(Ny,Nx); Dr(:) = R; D = Dr'; case 4 kd = vl_kdtreebuild(x'); [i,d] = vl_kdtreequery(kd,x',y','NumNeighbors',Nx); [j,k] = sort(i); D = sqrt(d(k)); case 5 % it is like 3 but with out sqrt xs = zeros(1,n,Nx); xs(:) = x'; Sx = repmat(xs,[Ny 1 1]); Sx = Sx-repmat(y,[1 1 Nx]); Sx = Sx.*Sx; R = sum(Sx,2); Dr = zeros(Ny,Nx); Dr(:) = R; D = Dr'; end
github
domingomery/Balu-master
andsift.m
.m
Balu-master/Miscellaneous/andsift.m
714
utf_8
783f127c786620dfefdb1c28025e7cb7
% It separates sift descriptors into descriptors that belong to the region % of interest R. R is a binary image. fi,di are the frames and descriptors % of pixels = i (for i=0,1). (ff,dd) is the transposed output of vl_sift. function [f1,d1,f0,d0,i1,i0] = andsift(ff,dd,R) f = ff'; d = dd'; [N,M] = size(R); ii = round(f(2,:)); jj = round(f(1,:)); kk = (ii<1)|(jj<1)|(ii>N)|(jj>M); ii(kk) = []; jj(kk) = []; kk = sub2ind([N M],ii,jj); if ~isempty(kk) r1 = R(kk); i1 = find(r1==1); i0 = find(r1==0); f1 = f(:,i1); d1 = d(:,i1); f0 = f(:,i0); d0 = d(:,i0); else f1 = []; d1 = []; f0 = f; d0 = d; end f1 = f1'; d1 = d1'; f0 = f0'; d0 = d0';
github
domingomery/Balu-master
howis.m
.m
Balu-master/Miscellaneous/howis.m
489
utf_8
08b5567797d8a802206bf707280552b5
% howis(x) % % Toolbox: Balu % How is x? it displays min, max, size, class of x. % If x is a structure, it display the field names. % % D.Mery, PUC-DCC, Jul 2009-2012 % http://dmery.ing.puc.cl % function howis(x) if isstruct(x) disp('Structure:') x else fprintf('%s\n',['min = ' num2str(min(x(:)))]) fprintf('%s\n',['max = ' num2str(max(x(:)))]) fprintf('%s\n',['size = ' num2str(size(x))]) fprintf('%s\n',['class = ' class(x)]) end
github
domingomery/Balu-master
Bfx_centroid.m
.m
Balu-master/Examples/Bfx_centroid.m
1,071
utf_8
535fc870f63dc5c0db9c6cd5bd5a99fc
% [X,Xn] = Bfx_centroid(R,options) % % Toolbox: Balu % % Centroid of a region. % % options.show = 1 display mesagges. % % X(1) is centroid-i, X(2) is centroid-j % Xn is the list of the n feature names. % % Example (Centroid of a region) % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % imshow(R); % options.show = 1; % [X,Xn] = Bfx_centroid(R,options); % Bio_printfeatures(X,Xn) % % See also Bfx_basicgeo, Bfx_gupta, Bfx_fitellipse, Bfx_flusser, % Bfx_hugeo. % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl function [X,Xn] = Bfx_centroid(R,options) if options.show == 1 disp('--- extracting centroid...'); end [Ireg,Jreg] = find(R==1); % pixels in the region ic = mean(Ireg); jc = mean(Jreg); X = [ic jc]; Xn = [ 'Centroid i ' 'Centroid j ']; % 24 characters per name if options.show == 1 clf imshow(R) hold on plot(X(2),X(1),'rx') enterpause end
github
domingomery/Balu-master
Bex_sfssvm.m
.m
Balu-master/Examples/Bex_sfssvm.m
1,028
utf_8
e44139735f36fbd1b9b4572ee25ad370
% s = Bex_sfssvm(f,d,m) % % Toolbox: Balu % Example: Feature selection using Balu algorithm based on SFS and SVM. % % Bfs_balu has three steps: % (1) normalizes (using Bft_norm), % (2) cleans (using Bfs_clean), and % (3) selects features (using Bfs_sfs). % % Example: % load datareal % s = Bex_sfssvm(f,d,6) % fn(s,:) % % See also Bfs_balu % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl function s = Bex_sfssvm(f,d,m) op.m = m; % m features will be selected op.s = 0.75; % only 75% of sample will be used op.show = 1; % display results op.b.name = 'svm'; % SFS with SVM op.b.options.kernel = 4; % SVM-RBF s = Bfs_balu(f,d,op); % index of selected features X = f(:,s); % selected features op = op.b.options; [X1,d1,X2,d2] = Bds_stratify(X,d,0.75); d2s = Bcl_svm(X1,d1,X2,op); p = Bev_performance(d2,d2s); % performance with lsef fprintf('Performance with SFS and SVM = %5.4f\n',p)
github
domingomery/Balu-master
Bex_decisionline.m
.m
Balu-master/Examples/Bex_decisionline.m
707
utf_8
49c2a2387a4afed7977a6df45a94a357
% Bex_decisionline(X,d,bcl) % % Toolbox: Balu % Example: Decision lines of features X with labels d for classifiers % defined in bcl % % Example: % load datagauss % simulated data (2 classes, 2 features) % Xn = ['x_1';'x_2']; % bcl(1).name = 'knn'; bcl(1).options.k = 5; % KNN with 5 neighbors % bcl(2).name = 'lda'; bcl(2).options.p = []; % LDA % bcl(3).name = 'svm'; bcl(3).options.kernel = 3; % rbf-SVM % Bex_decisionline(X,d,bcl) % % See also Bio_decisionline % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl function Bex_decisionline(X,d,bcl) op = Bcl_structure(X,d,bcl); Bio_decisionline(X,d,['x1';'x2'],op);
github
domingomery/Balu-master
Bex_exsknn.m
.m
Balu-master/Examples/Bex_exsknn.m
1,344
utf_8
1cc04f149ac136e42e9984448caeee04
% s = Bex_exsknn(f,d,m) % % Toolbox: Balu % Example: Feature selection using exhaustive search and KNN. % % Bfs_balu has three steps: % (1) normalizes (using Bft_norm), % (2) cleans (using Bfs_clean), and % (3) selects features (using Bfs_sfs). % % Example: % load datareal % s = Bex_exsknn(f,d) % fn(s,:) % % See also Bfs_balu % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl function s = Bex_exsknn(f,d) op.m = 10; % 10 features will be pre-selected op.s = 0.75; % only 75% of sample will be used op.show = 1; % display results op.b.name = 'fisher'; % SFS with fisher s1 = Bfs_balu(f,d,op); % index of selected features X1 = f(:,s1); % selected features op.m = 4; % 3 features will be selected op.show = 1; % display results op.b.name = 'knn'; % SFS with KNN op.b.options.k = 5; % 5 neighbors s2 = Bfs_exsearch(X1,d,op); % index of selected features s = s1(s2); % list of feature names X = f(:,s); op = op.b.options; [X1,d1,X2,d2] = Bds_stratify(X,d,0.75); d2s = Bcl_knn(X1,d1,X2,op); p = Bev_performance(d2,d2s); % performance with lsef fprintf('Performance with exhaustive search and KNN = %5.4f\n',p)
github
domingomery/Balu-master
Bex_fscombination.m
.m
Balu-master/Examples/Bex_fscombination.m
3,104
utf_8
4470da31ed3e0aa327ccb8d95e0cbbff
% Bex_fscombination % % Toolbox: Balu % Combination of feature selection algorithms. % % This example shows how to combine different feature selection algorthm % in orde to obtain the highest performance. % % The evaluation of the performance is using a simple LDA classifier % % Example: % load datareal % Bex_fscombination % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl function Bex_fscombination(f,d) op_sfs.m = 40; % 40 features will be selected op_sfs.s = 1; % 100% of sample will be used op_sfs.show = 1; % display results op_sfs.b.name = 'fisher'; % SFS with Fisher s = Bfs_balu(f,d,op_sfs); % index of selected features XSFS40 = f(:,s); % SFS first 40 features XPCA40 = Bft_pca(f,40); % first 40 principal components disp('1. Feature selection with SFS...') X = XSFS40(:,1:6); lda_performance(X,d) % function at the end of this code disp('2. Feature selection with PCA only...') X = XPCA40(:,1:6); lda_performance(X,d) disp('3. Feature selection with PCA of SFS...') X = Bft_pca(XSFS40,6); % first 6 principal components lda_performance(X,d) % function at the end of this code disp('4. Feature selection with SFS of PCA and SFS...') X1 = [XPCA40 XSFS40]; op_sfs.m = 6; % 6 features will be selected s = Bfs_balu(X1,d,op_sfs); % index of selected features X = X1(:,s); lda_performance(X,d) % function at the end of this code disp('5. Feature selection with SFS of PCA of SFS...') X1 = Bft_pca(XSFS40,20); % X1 from last step X2 = [X1 XSFS40]; s = Bfs_balu(X2,d,op_sfs); % index of selected features X = X2(:,s); lda_performance(X,d) % function at the end of this code disp('6. Feature selection with SFS of PCA and all features...') % (c) Esteban Cortazar, 2010 X1 = [XPCA40 f]; s = Bfs_balu(X1,d,op_sfs); % index of selected features X = X1(:,s); lda_performance(X,d) % function at the end of this code disp('7. Feature selection with LSEF of SFS...') op2.m = 6; % 5 features will be selected op2.show = 0; % display results s = Bfs_lsef(XSFS40,op2); % index of selected features X = X1(:,s); lda_performance(X,d) % function at the end of this code disp('8. Feature selection with FOSMOD of SFS...') s = Bfs_fosmod(XSFS40,op2);% data from last step X = X1(:,s); lda_performance(X,d) % function at the end of this code disp('9. Feature selection with PLSR of SFS...') X = Bft_plsr(XSFS40,d,6); lda_performance(X,d) % function at the end of this code end function lda_performance(X,d) op_lda.p = []; ds = Bcl_lda(X,d,X,op_lda); Bev_performance(d,ds) enterpause end
github
domingomery/Balu-master
Bex_lsef.m
.m
Balu-master/Examples/Bex_lsef.m
1,379
utf_8
80041176a9d5dd6cf64549a184d4ad9b
% s = Bex_lsef(f,d,m) % % Toolbox: Balu % Example: Feature selection using lsef algorithm % % Example: % load datareal % s = Bex_lsef(f,d,6) % fn(s,:) % % See also Bfs_lsef % % (c) GRIMA-DCCUC, 2011 % http://grima.ing.puc.cl function s = Bex_lsef(f,d,m) op.m = 2*m; % 2*m features will be selected using SFS op.s = 0.75; % only 75% of sample will be used op.show = 1; % display results op.b.name = 'fisher'; % SFS with Fisher s1 = Bfs_balu(f,d,op); % index of selected features X1 = f(:,s1); % preselected features op.m = m; % m/2 features will be selected op.show = 1; % display results [s2,Y,th] = Bfs_lsef(X1,op); % Y is computed as A*th, where % A = [X1(:,s2) ones(size(X1,1),1)] Ypca = Bft_pca(X1,0.95); % PCA analysis mse(Y-Ypca) % Y and Ypca are very similar. T1 = X1(:,s2); % selected features (transformation op.p = []; ds1 = Bcl_lda(T1,d,T1,op); p1 = Bev_performance(d,ds1); % performance with lsef T2 = Bft_pca(X1,op.m); % transformed features using PCA op.p = []; ds2 = Bcl_lda(T2,d,T2,op); p2 = Bev_performance(d,ds2); % performance with PCA fprintf('Performance with lsef = %5.4f, with PCA = %5.4f\n',p1,p2) s = s1(s2);
github
domingomery/Balu-master
Bfs_clean.m
.m
Balu-master/FeatureSelection/Bfs_clean.m
1,773
utf_8
13cedc8d94836230ab53973127f23964
% selec = Bfs_clean(X,show) % % Toolbox: Balu % Feature selection cleaning. % % It eliminates constant features and correlated features. % % Input: X is the feature matrix. % show = 1 displays results (default show=0) % Output: selec is the indices of the selected features % % Example: % load datareal % s = Bfs_clean(f,1); % index of selected features % X = f(:,s); % selected features % Xn = fn(s,:); % list of feature names % disp('Original:'); howis(f) % original set of features % disp('Selected:'); howis(X) % set of selecte features % % D.Mery, PUC-DCC, Jul. 2009 % http://dmery.ing.puc.cl function selec = Bfs_clean(X,show) f = X; if not(exist('show','var')) show = 0; end nf = size(f,2); p = 1:nf; ip = zeros(nf,1); % eliminating correlated features warning off C = abs(corrcoef(f)); warning on [ii,jj] = find(C>0.99); if (not(isempty(ii))) for i=1:length(ii) if (abs(ii(i)-jj(i))>0) k = max([ii(i) jj(i)]); t = find(p==k); n = length(p); if (not(isempty(t))) if (t==1) p = p(2:n); else if (t==n) p = p(1:n-1); else p = p([1:t-1 t+1:n]); end end end end end end ip(p) = 1; % eliminating constant features s = std(f); ii = find(s<1e-8); if not(isempty(ii)) ip(ii) = 0; end p = find(ip); fc = f(:,p); nc = size(fc,2); if show fprintf('Bfs_clean: number of features reduced from %d to %d.\n',nf,nc) end selec=p;
github
domingomery/Balu-master
Bfs_sfscorr.m
.m
Balu-master/FeatureSelection/Bfs_sfscorr.m
1,392
utf_8
42d6288b4c73a7cbcc34d92b3fa48c76
% [R,selec] = Bfa_sfscorr(f,d,m) % % Toolbox: Balu % Sequential Forward Selection for features f according to measurment d. % The algorithm searchs the linear combination of the features that % best correlates with d. % m features will be selected. % R is the obtained correlation coefficient and selec are the number of the % selected features. % % D.Mery, PUC-DCC, Aug. 2008 % http://dmery.ing.puc.cl % function [R,selec] = Bfa_sfscorr(f,d,m) selec = []; %selected features R = []; Rmax = 0; k=1; while (k<=m) nuevo = 0; for i=1:size(f,2) if (k==1) || (sum(selec==i)==0) if std(f(:,i))>0 s = [selec i]; fs = f(:,s); [per,Rs] = Bfa_corrsearch(fs,d,1,2,0); if (Rs>Rmax) ks = i; Rmax = Rs; nuevo = 1; end end end end if (nuevo) selec = [selec ks]; R = [R Rmax]; clf bar(R) hold on for i=1:length(selec) text(i-0.4,R(i)*1.05,sprintf('%d',selec(i))); end pause(0) k = k + 1; else disp('no more improvement, the sequantial search is interrupted.'); k = 1e10; end end figure Bfa_corrsearch(f(:,selec),d,1,2,1);
github
domingomery/Balu-master
Bfs_noposition.m
.m
Balu-master/FeatureSelection/Bfs_noposition.m
1,380
utf_8
6d584f9b6a2290b942e2363403888915
% [f_new,fn_new] = Bfs_noposition(f,fn) % % Toolbox: Balu % This procedure deletes the features related to the position. % It deletes the following features: % - center of grav i % - center of grav j % - Ellipse-centre i % - Ellipse-centre j % % Example: % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % [X1,Xn1] = Bfx_basicgeo(R); % basic geometric features % [X2,Xn2] = Bfx_fitellipse(R); % Ellipse features % X3 = [X1 X2]; Xn3 =[Xn1;Xn2]; % fprintf('\nOriginal features\n'); % Bio_printfeatures(X3,Xn3) % [X4,Xn4] = Bfs_noposition(X3,Xn3); % delete position features % fprintf('\nSelected features\n'); % Bio_printfeatures(X4,Xn4) % % See also Bfs_norotation, Bfs_nobackground. % % D.Mery, PUC-DCC, Nov. 2009 % http://dmery.ing.puc.cl function [f_new,fn_new] = Bfs_noposition(f,fn) s = ['center of grav i [px] ' 'center of grav j [px] ' 'Ellipse-centre i [px] ' 'Ellipse-centre j [px] ']; [n,m] = size(s); M = size(fn,1); f_new = f; fn_new = fn; ii = []; for i=1:n; D = sum(abs(fn(:,1:m)-ones(M,1)*s(i,:)),2); ii = [ii; find(D==0)]; end if not(isempty(ii)) f_new(:,ii) = []; fn_new(ii,:) = []; end
github
domingomery/Balu-master
Bfs_fosmod.m
.m
Balu-master/FeatureSelection/Bfs_fosmod.m
3,173
utf_8
459b2c4292d50ca2234e5e3f78eda0fc
% selec = Bfs_fosmod(X,options) % % Toolbox: Balu % Feature Selection using FOS-MOD algorithm % % input: X feature matrix % options.m number of features to be selected % options.show = 1 displays results % % output: selec selected features % % FOS_MOD is a forward orthogonal search (FOS) algorithm by maximizing % the overall dependency (MOD). The algorithm assumes that a linear % relationship exists between sample features: % % Reference: % Wei, H.-L. & Billings, S. Feature Subset Selection and Ranking for % Data Dimensionality Reduction Pattern Analysis and Machine % Intelligence, IEEE Transactions on, 2007, 29, 162-166 % % Example: % load datareal % s1 = [279 235 268 230 175 165 207 160 269 157]; %indices using Example % %of Bfs_sfs. % X1 = f(:,s1); % preselected features % Xn1 = fn(s1,:); % op.m = 5; % 5 features will be selected % op.show = 1; % display results % s = Bfs_fosmod(X1,op); % index of selected features % T1 = X1(:,s); % selected features (transformation % % is avoided) % op.p = []; % ds1 = Bcl_lda(T1,d,T1,op); % p1 = Bev_performance(d,ds1) % performance with fosmod % T2 = Bft_pca(X1,op.m); % transformed features using PCA % op.p = []; % ds2 = Bcl_lda(T2,d,T2,op); % p2 = Bev_performance(d,ds2) % performance with PCA % fprintf('Performance with fosmod = %5.4f, with PCA = %5.4f\n',p1,p2) % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function selec = Bfs_fosmod(X,d,options) % d is not used by this algorithm. % the sintaxis "Bfs_fosmod(X,d,options)" is allowed in order to be % similar to other Bfs_ functions. if nargin==2; options = d; end m = options.m; show = options.show; [N,n] = size(X); % number of instances (samples), number of features l = zeros(m,1); p = ones(n,1); q = zeros(N,n); for mm=1:m if mm==1 Q = X; else Q = zeros(N,n); for j=1:n if p(j) alj = X(:,j); qm = alj; for k=1:mm-1 qm = qm - ((alj'*q(:,k))/(q(:,k)'*q(:,k)))*q(:,k); end Q(:,j) = qm; end end end C = zeros(n,n); for j=1:n if p(j) for i=1:n C(i,j) = Bfa_sqcorrcoef(X(:,i),Q(:,j)); end end end Cm = mean(C); [i,l(mm)] = max(Cm); p(l(mm)) = 0; q(:,mm) = Q(:,l(mm)); err = zeros(n,mm); for k=1:mm for j=1:n err(j,k) = Bfa_sqcorrcoef(X(:,j),q(:,k))*100; end end if mm>1 serr = sum(err,2); else serr = err; end mserr = mean(serr); if show fprintf('%2d) selected feature=%4d error=%7.2f%%\n',mm,l(mm),100-mserr) end end selec = l;
github
domingomery/Balu-master
Bfs_random.m
.m
Balu-master/FeatureSelection/Bfs_random.m
2,187
utf_8
99545454631b8da08b171978d75886f7
% selec = Bfs_random(X,d,options) % % Toolbox: Balu % Select best features from random subsets of X according to ideal % classification d. % options.m is the number features will be selected. % options.M is the number of random subsets to be tested. % options.b.method = 'fisher' uses Fisher objetctive function. % options.b.method = 'sp100' uses as criteria Sp @Sn=100%. % options.b can be any Balu classifier structure (see example). % options.show = 1 display results. % selec is the indices of the selected features. % % Example 1: Feature selection using Fisher dicriminant % load datareal % op.m = 10; % 10 features will be selected % op.M = 1000; % number of random sets to be tested % op.show = 1; % display results % op.b.name = 'fisher'; % Feature score % s = Bfs_random(f,d,op); % index of selected features % X = f(:,s); % selected features % Xn = fn(s,:) % list of feature names % % Example 2: Feature selection using a KNN classifier % load datareal % op.m = 10; % 10 features will be selected % op.M = 1000; % number of random sets to be tested % op.show = 1; % display results % op.b.name = 'knn'; % Feature score is the performance % op.b.options.k = 5; % 5 neighbors % s = Bfs_random(f,d,op); % index of selected features % X = f(:,s); % selected features % Xn = fn(s,:) % list of feature names % % (c) D.Mery, PUC-DCC, Jul. 2011 % http://dmery.ing.puc.cl function selec = Bfs_random(X,d,options) m = options.m; M = options.M; show = options.show; s0 = Bfs_clean(X); f = X(:,s0); nf = size(f,2); Jmax = 0; k = 0; while (k<=M) N = rand(nf,1); [i,j] = sort(N); s = j(1:m); fs = f(:,s); Js = Bfa_score(fs,d,options); if (Js>Jmax) selec = s; Jmax = Js; if show fprintf('Jmax = %8.4f\n',Jmax); end end k = k+1; end
github
domingomery/Balu-master
Bfs_norotation.m
.m
Balu-master/FeatureSelection/Bfs_norotation.m
1,537
utf_8
b1c6fa0ea43372e402874e2f3e6db857
% [f_new,fn_new] = Bfs_norotation(f,fn) % % Toolbox: Balu % This procedure deletes all no rotation invariant features. % It deletes the features that have in their name the strings: % - orient % - Gabor( % - [8,u2] for LBP % - sLBP % % Example: % options.b = Bfx_build({'haralick','lbp'}); % options.colstr = 'rgb'; % R image % I = imread('testimg1.jpg'); % input image % R = Bim_segbalu(I); % segmentation % [X,Xn] = Bfx_int(I,R,options); % intensity features % [X1,Xn1] = Bfs_norotation(X,Xn); % Bio_printfeatures(X1,Xn1) % % % See also Bfs_noposition, Bfs_nobackground. % % D.Mery, PUC-DCC, May 2012 % http://dmery.ing.puc.cl function [f_new,fn_new] = Bfs_norotation(f,fn) f_new = f; fn_new = fn; [ix,fn_new] = Bio_findex(fn_new,'Orientation',0); f_new = f_new(:,ix); [ix,fn_new] = Bio_findex(fn_new,'Ellipse-orient',0); f_new = f_new(:,ix); [ix,fn_new] = Bio_findex(fn_new,'Gabor(',0); f_new = f_new(:,ix); [ix,fn_new] = Bio_findex(fn_new,'[8,u2]',0); f_new = f_new(:,ix); [ix,fn_new] = Bio_findex(fn_new,'sLBP' ,0); f_new = f_new(:,ix); [ix,fn_new] = Bio_findex(fn_new,'Fourier Abs (' ,0); f_new = f_new(:,ix); [ix,fn_new] = Bio_findex(fn_new,'Fourier Ang (' ,0); f_new = f_new(:,ix); [ix,fn_new] = Bio_findex(fn_new,'DCT(' ,0); f_new = f_new(:,ix);
github
domingomery/Balu-master
Bfs_all.m
.m
Balu-master/FeatureSelection/Bfs_all.m
131
utf_8
844e98d7bb621a3acffe6f60df432c78
% Dummy file called by Bfx_gui % It selects all features of X. function selec = Bfs_all(X,d,options) m = size(X,2); selec = (1:m)';
github
domingomery/Balu-master
Bfs_balu.m
.m
Balu-master/FeatureSelection/Bfs_balu.m
2,884
utf_8
553453caae55239bed210fd8551d179a
% selec = Bfs_balu(X,d,options) % % Toolbox: Balu % Feature selection of "best" options.m features of X to ideal % classification d. This function uses only a portion of options.s % samples to select the features. % Bfs_balu (1) normalizes (using Bft_norm), (2) cleans (using Bfs_clean) % and (3) selects features (using Bfs_sfs). % options.b.method = 'fisher' uses Fisher objetctive function. % options.b.method = 'sp100' uses as criteria Sp @Sn=100%. % options.b can be any Balu classifier structure (see example). % options.show = 1 display results. % selec is the indices of the selected features. % % Example 1: Balu feature selection using Fisher dicriminant % load datareal % op.m = 10; % 10 features will be selected % op.s = 0.75; % only 75% of sample will be used % op.show = 1; % display results % op.b.name = 'fisher'; % SFS with Fisher % s = Bfs_balu(f,d,op); % index of selected features % X = f(:,s); % selected features % Xn = fn(s,:) % list of feature names % % Example 2: Balu feature selection using a KNN classifier % load datareal % op.m = 10; % 10 features will be selected % op.s = 0.75; % only 75% of sample will be used % op.show = 1; % display results % op.b.name = 'knn'; % SFS with KNN % op.b.options.k = 5; % 5 neighbors % s = Bfs_balu(f,d,op); % index of selected features % X = f(:,s); % selected features % Xn = fn(s,:) % list of feature names % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function selec = Bfs_balu(X,d,options) s = options.s; show = options.show; m = options.m; if (s<0)||(s>1) error('Bfs_balu: options.s must be between 0 and 1...') end fT = X; dT = d; if show close all end if s<1 [f,d] = Bds_stratify(fT,dT,s); else f = X; end % cleaning if show disp('eliminating no relevant and correlated features...'); end selec0 = Bfs_clean(f); f = f(:,selec0); % normalize if show disp('normalizing features...'); end ff = Bft_norm(f,1); % selection if show disp('selecting features...'); end M = size(ff,2); if M<m error('Bfs_balu: number of features to be selected (%d) is larger than number of existing features (%d)',M,m); end warning off %#ok<WNOFF> N = nchoosek(M,m); warning on %#ok<WNON> if N>10000 if show disp('selecting features using SFS...'); end selec = Bfs_sfs(ff,d,options); else if show disp('selecting features using exhaustive search...'); end selec = Bfs_exsearch(ff,d,options); end selec = selec0(selec);
github
domingomery/Balu-master
Bfs_mRMR.m
.m
Balu-master/FeatureSelection/Bfs_mRMR.m
4,499
utf_8
e8736538d2bdd540fea3d416d8e0dee6
% selec = Bfs_mRMR(X,d,options) % % Toolbox: Balu % Feature selection using Criteria of Max-Dependency, Max-Relevance, and % Min-Redundancy after Peng et al. (2005) % % X extracted features (NxM): N samples, M features % d ideal classification (Nx!) for the N samples % options.m number of selected features % options.p a priori probability of each class (if not given, is % estimated using the ratio samples per class to N. % % References: % Peng, H.; Long, F.; Ding, C. (2005): Feature Selection Based on Mutual % Information: Criteria of Max-Dependency, Max-Relevance, and Min- % Redundancy. IEEE Trans. on Pattern Analysis and Machine Intelligence, % 27(8):1226-1238. % % Z. I. Botev, J. F. Grotowski, and D. P. Kroese (2010): Kernel density % estimation via diffusion Annals of Statistics, 38(5):2916-2957. % % NOTE: % The pdf's are estimated using Kernel Density Estimations programs % kde.m and kde2d.m after Botev et al. (2010) implemented by Botev. % These files are in Balu directory 'Feature Analysis' as Bfa_kde and % Bfs_kde2d. They can also be downloaded from www.mathwork.com % (c) Zdravko Botev. All rights reserved. % % Example (comparison between SFS-Fisher and mRMR): % % load datareal % s = Bfs_clean(f,1); % X = f(:,s); % k = 0; % k=k+1;b(k).name = 'knn'; b(k).options.k = 9; % KNN with 9 neighbors % k=k+1;b(k).name = 'lda'; b(k).options.p = []; % LDA % k=k+1;b(k).name = 'qda'; b(k).options.p = []; % QDA % k=k+1;b(k).name = 'dmin'; b(k).options = []; % Euclidean distance % k=k+1;b(k).name = 'maha'; b(k).options = []; % Mahalanobis distance % k=k+1;b(k).name = 'libsvm'; b(k).options.kernel = '-t 2'; % rbf-SVM % k=k+1;b(k).name = 'nnglm'; b(k).options.method = 3; b(k).options.iter = 10; % Nueral network % % op.strat=1; op.b = b; op.v = 10; op.show = 1; op.c = 0.95; % 10 groups cross-validation % % msel1 = 12; % msel2 = 4; % % op1.m = msel1;op1.show=1;op1.b.name='fisher'; % s1 = Bfs_sfs(X,d,op1); % X1 = X(:,s1); % disp('Performances using SFS-Fisher:') % p1 = Bev_crossval(X1(:,1:msel2),d,op); % % op2.m = msel2;op2.show=1; % s2 = Bfs_mRMR(X1,d,op2); % disp(' ') % disp('Performances using SFS-mRMR:') % p2 = Bev_crossval(X1(:,s2),d,op); % disp(' ') % disp('Comparison of performances and mean of performances:') % [p1 p2], mean([p1 p2]) % % D.Mery, PUC-DCC, Jul. 2011 % http://dmery.ing.puc.cl function s = Bfs_mRMR(X,d,options) if ~isfield(options,'p') dn = max(d)-min(d)+1; % number of classes p = ones(dn,1)/dn; else p = options.p; end if ~isfield(options,'show') show = 0; else show = options.show; end % T = 100; M = size(X,2); n = options.p; s = zeros(n,1); t = ones(M,1); h = zeros(n,1); ff = Bio_statusbar('Bfs_mRMR'); Ic = zeros(M,1); m = 1; for j=1:M % Ic(j) = Bfa_mutualinfo(X(:,j),d,p); % see in paper I(xj;c) Ic(j) = Bfa_miparzen2([X(:,j) d],1,p); % see in paper I(xj;c) end ff = Bio_statusbar(1/n,ff); [Icmax,jsel] = max(Ic); if show clf h(m) = Icmax; bar(h); end s(m) = jsel; t(jsel) = 0; MI = zeros(M,M); if n>1 for m=2:n Jmax = -Inf; for j=1:M if t(j)==1 % if yes, feature j is not selected xj = X(:,j); sumI = 0; for i=1:m-1 xi = X(:,s(i)); % sumI = sumI + Bfa_mutualinfo2([xj xi]); % see in paper I(xj;xi) if MI(s(i),j)==0; mij = Bfa_miparzen2([xj xi]); MI(s(i),j) = mij; MI(j,s(i)) = mij; else mij = MI(s(i),j); end sumI = sumI + mij; % see in paper I(xj;xi) % sumI = sumI + Bfa_miparzen2([xj xi]); % see in paper I(xj;xi) end % Jj = Ic(j)-sumI/(m-1); Jj = Ic(j)/(sumI/(m-1)); % Jj = Ic(j)-sumI; if Jj>Jmax Jmax = Jj; jsel = j; end end end s(m) = jsel; t(jsel) = 0; if show h(m) = Jmax; bar(h) end ff = Bio_statusbar(m/n,ff); end end delete(ff)
github
domingomery/Balu-master
Bfs_bb.m
.m
Balu-master/FeatureSelection/Bfs_bb.m
4,988
utf_8
149d76a182777b35b877fa7080dc39a7
% selec = Bfs_bb(X,d,options) % % Toolbox: Balu % Feature selection using Branch & Bound for fatures X according to % ideal classification d. optins.m features will be selected. % options.b.method = 'fisher' uses Fisher objetctive function. % options.b.method = 'sp100' uses as criteria Sp @Sn=100%. % options.b can be any Balu classifier structure (see example). % options.show = 1 display results. % selec is the indices of the selected features. % % Example 1: Branch and Bound search from using Fisher dicriminant % (compare this example with exhaustive serach) % load datareal % s1 = [279 235 268 230 175 165 207 160 269 157]; %indices using Example % %of Bfs_sfs. % X1 = f(:,s1); % preselected features % Xn1 = fn(s1,:); % op.m = 3; % 3 features will be selected % op.show = 1; % display results % op.b.name = 'fisher'; % SFS with Fisher % s = Bfs_bb(X1,d,op); % index of selected features % X2 = X1(:,s); % selected features % Xn2 = Xn1(s,:) % list of feature names % % Example 2: Branch and Bound using a KNN classifier % (compare this example with exhaustive serach) % load datareal % s1 = [279 235 268 230 175 165 207 160 269 157]; %indices using Example % %of Bfs_sfs. % X1 = f(:,s1); % preselected features % Xn1 = fn(s1,:); % op.m = 4; % 3 features will be selected % op.show = 1; % display results % op.b.name = 'knn'; % SFS with KNN % op.b.options.k = 5; % 5 neighbors % s = Bfs_bb(X1,d,op); % index of selected features % X2 = X1(:,s); % selected features % Xn2 = Xn1(s,:) % list of feature names % % (c) Irene Zuccar, PUC-DCC, Jul. 2011 % http://grima.ing.puc.cl function selec = Bfs_bb(X,d,options) f = X; p = options.m; NumFeat = size(f,2); Bend = false; % Initial node in Bnode Bnode = nchoosek(1:NumFeat,NumFeat); % Score for initial node JBnode = Bfa_score(f,d,options); if isnan(JBnode) Bnode = [1,Bnode]; else Bnode = [JBnode,Bnode]; end % Add initial node to stack Bopened. Bopened = []; Bclosed = []; Bopened = [Bnode;Bopened]; bestJ = 0; selec = []; r = 0; while (~Bend) % Take Bnode from stack and store in Bclosed [Bopened,Bclosed,Bnode] = Bfs_bbpop(Bopened,Bclosed); JBnode=Bnode(1,1); % Prune criteria if JBnode > bestJ b = size(Bnode,2)-1; % If it has not reached the leaves then create the children of Bnode if b>p % It generates the children that have not already generated, % it computes the score and it stores and sorts in Bopened, % it takes the best one. h = Bfs_bbchild(Bnode,f,d,Bopened,Bclosed,options); Bopened = Bfs_bbpush(Bopened,h); end % If Bnode is a leave > update prune criteria, and store the % selected features if b == p bestJ = JBnode; selec = Bnode; end end % If empty stack then end search in tree a = size(Bopened,1); if a == 0 Bend = true; end % The best result in 10000 iterations r=r+1; if r==10000 Bend = true; error('Branch and bound for feature selection interrupted: too many iterations.') end end selec = selec(2:end)'; end function resp = Bfs_bbis(Bnode,Bopened,Bclosed) resp = false; m = size(Bopened,1); for i = 1:m if Bopened(i,2:end) == Bnode(2:end) resp = true; return; end end m = size(Bclosed,1); for i = 1:m if Bclosed(i,2:end) == Bnode(2:end) resp=true; return; end end end function resp = Bfs_bbchild(padre,f,d,Bopened,Bclosed,options) NumFeat = size(Bclosed,2)-1; nPadre = size(padre,2)-1; Bchild = nchoosek(padre(1,2:nPadre+1),nPadre-1); Bchild = [zeros(nPadre,1),Bchild]; Bchild = padarray(Bchild,[0,NumFeat-nPadre+1],0,'post'); resp=[]; for i=1:nPadre if ~Bfs_bbis(Bchild(i,:),Bopened,Bclosed) fchild = f(:,Bchild(i,2:nPadre)); % JBchild = Bfa_jfisher(fchild,d); JBchild = Bfa_score(fchild,d,options); Bchild(i,1) = JBchild; resp = [Bchild(i,:);resp]; end end resp = -sortrows(-resp); end function [Bopened,Bclosed,Bnode] = Bfs_bbpop(Bopened,Bclosed) Bnode = Bopened(1,:); Bclosed = [Bnode;Bclosed]; aux=Bnode(2:end); pos = find(aux==0); q = size(pos,2); if q~=0 Bnode(pos+1:end) = []; end Bopened(1,:) = []; end function Bopened = Bfs_bbpush(Bopened,h) Bopened = [h;Bopened]; end
github
domingomery/Balu-master
Bfs_nobackground.m
.m
Balu-master/FeatureSelection/Bfs_nobackground.m
1,499
utf_8
98cdc4bfb82c9a67adee6e5799d28faa
% [f_new,fn_new] = Bfs_nobackground(f,fn) % % Toolbox: Balu % This procedure deletes the features related to the position. % It deletes the following features related to the contrast: % - contrast-K1 % - contrast-K2 % - contrast-K3 % - contrast-Ks % - contrast-K % % Example: % options.show = 1; % display results % options.neighbor = 2; % neigborhood is imdilate % options.param = 5; % with 5x5 mask % I = imread('testimg4.jpg'); % input image % J = I(395:425,415:442,1); % region of interest (red) % R = J<=130; % segmentation % figure;imshow(J,[]) % figure;imshow(R) % [X1,Xn1] = Bfx_contrast(J,R,options); % contrast features % options.mask = 5; % display results % [X2,Xn2] = Bfx_basicint(J,R,options); % X3 = [X1 X2]; Xn3 =[Xn1;Xn2]; % fprintf('\nOriginal features\n'); % Bio_printfeatures(X3,Xn3) % [X4,Xn4] = Bfs_nobackground(X3,Xn3); % delete contrast features % fprintf('\nSelected features\n'); % Bio_printfeatures(X4,Xn4) % % D.Mery, PUC-DCC, May 2012 % http://dmery.ing.puc.cl function [f_new,fn_new] = Bfs_nobackground(f,fn) [ix,fn_new] = Bio_findex(fn,'contrast',0); f_new = f(:,ix);
github
domingomery/Balu-master
Bfs_exsearch.m
.m
Balu-master/FeatureSelection/Bfs_exsearch.m
2,602
utf_8
74412cf1479a6c06be68936e449dcd5a
% selec = Bfs_exsearch(X,d,options) % % Toolbox: Balu % Feature selection using exhaustive search for fatures X according to % ideal classification d. optins.m features will be selected. % options.b.method = 'fisher' uses Fisher objetctive function. % options.b.method = 'sp100' uses as criteria Sp @Sn=100%. % options.b can be any Balu classifier structure (see example). % options.show = 1 display results. % selec is the indices of the selected features. % % Example 1: Exhaustive search from using Fisher dicriminant % load datareal % s1 = [279 235 268 230 175 165 207 160 269 157]; %indices using Example % %of Bfs_sfs. % X1 = f(:,s1); % preselected features % Xn1 = fn(s1,:); % op.m = 3; % 3 features will be selected % op.show = 1; % display results % op.b.name = 'fisher'; % SFS with Fisher % s = Bfs_exsearch(X1,d,op); % index of selected features % X2 = X1(:,s); % selected features % Xn2 = Xn1(s,:) % list of feature names % % Example 2: Exhaustive serach using a KNN classifier % load datareal % s1 = [279 235 268 230 175 165 207 160 269 157]; %indices using Example % %of Bfs_sfs. % X1 = f(:,s1); % preselected features % Xn1 = fn(s1,:); % op.m = 4; % 4 features will be selected % op.show = 1; % display results % op.b.name = 'knn'; % Feature selection using KNN % op.b.options.k = 5; % 5 neighbors % s = Bfs_exsearch(X1,d,op); % index of selected features % X2 = X1(:,s); % selected features % Xn2 = Xn1(s,:) % list of feature names % % D.Mery, PUC-DCC, Jul. 2011 % http://dmery.ing.puc.cl function selec = Bfs_exsearch(X,d,options) m = options.m; show = options.show; f = X; M = size(f,2); N = nchoosek(M,m); if (N>10000) ok = input(sprintf('Exhaustive Search needs %d evaluations... continue [yes=1/no=0]?',N)); if not(ok) error('Exhaustive search for feature selection interrupted.') end end T = nchoosek(1:M,m); Jmax = 0; for i=1:N fs = f(:,T(i,:)); Js = Bfa_score(fs,d,options); if (Js>Jmax) Jmax = Js; ks = i; if show fprintf('step=%2d/%d J=%f\n',i,N,Jmax) end end end selec = T(ks,:)';
github
domingomery/Balu-master
Bfs_ransac.m
.m
Balu-master/FeatureSelection/Bfs_ransac.m
1,759
utf_8
f416554f1291419b4b55cfb98cc3c01b
% selec = Bfsransac(X,d,m,show,method,param,param2,param3) % % Toolbox: Balu % Sequential Forward Selection for fatures X according to ideal % classification d. m features will be selected. % method = 'fisher' uses Fisher objetctive function (in this case param % is the a priori probability of each class, if not given it will be % assumed constant). % method = 'sp100' uses as criteria Sp @Sn=100%. % method could be any classifier implemented in Balu with the % corresponding parameters, e.g., method = 'knn' and param = 10, it will % select the best m features for 10 nearest neighbours. % show = 1 display results. % selec is the indices of the selected features. % % D.Mery, PUC-DCC, Ago. 2010 % http://dmery.ing.puc.cl % function selec = Bfsransac(X,d,m,show,method,varargin) s0 = Bfsclean(X); f = X(:,s0); nf = size(f,2); selec = []; %selected features Jmax = 0; dn = max(d)-min(d)+1; % number of classes if not(exist('show','var')) show = 0; end if not(exist('method','var')) method = 'fisher'; end k = 0; while (k<=300) [f1,d1] = Bstratify(f,d,0.67); s = Bfsfs(f1,d1,m); fs = f(:,s); switch lower(method) case 'fisher' if (not(exist('param','var'))) p = ones(dn,1)/dn; end Js = jfisher(fs,d,p); case 'sp100' Js = sp100(fs,d); otherwise e = ['ds = ' method '(fs,d,fs,varargin{:});']; eval(e); Js = Bperformance(d,ds); end if (Js>Jmax) selec = s; Jmax = Js; if show fprintf('Jmax = %8.4f\n',Jmax); end end k = k+1; end
github
domingomery/Balu-master
Bfs_sfs.m
.m
Balu-master/FeatureSelection/Bfs_sfs.m
3,719
utf_8
f9620a7255abdf0e8d1fe5a3fe189ce1
% selec = Bfs_sfs(X,d,options) % % Toolbox: Balu % Sequential Forward Selection for fatures X according to ideal % classification d. optins.m features will be selected. % options.b.method = 'fisher' uses Fisher objetctive function. % options.b.method = 'sp100' uses as criteria Sp @Sn=100%. % options.b can be any Balu classifier structure (see example). % options.show = 1 display results. % selec is the indices of the selected features. % % Example 1: SFS using Fisher dicriminant % load datareal % op.m = 10; % 10 features will be selected % op.show = 1; % display results % op.b.name = 'fisher'; % SFS with Fisher % s = Bfs_sfs(f,d,op); % index of selected features % X = f(:,s); % selected features % Xn = fn(s,:) % list of feature names % op_lda.p = []; % ds = Bcl_lda(X,d,X,op_lda); % LDA classifier % p = Bev_performance(d,ds) % performance with sfs % % Example 2: SFS using a KNN classifier % load datareal % op.m = 10; % 10 features will be selected % op.show = 1; % display results % op.b.name = 'knn'; % SFS with KNN % op.b.options.k = 5; % 5 neighbors % s = Bfs_sfs(f,d,op); % index of selected features % X = f(:,s); % selected features % Xn = fn(s,:) % list of feature names % % Example 3: SFS using sp100 criterion % load datareal % op.m = 10; % 10 features will be selected % op.show = 1; % display results % op.b.name = 'sp100'; % SFS with sp100 criterion % s = Bfs_sfs(f,d,op); % index of selected features % X = f(:,s); % selected features % Xn = fn(s,:) % list of feature names % % (c) D.Mery, PUC-DCC, Jul. 2011 % http://dmery.ing.puc.cl function selec = Bfs_sfs(X,d,options) m = options.m; show = options.show; if ~isfield(options,'force') options.force = 0; end force = options.force; f = X; N = size(f,2); selec = []; %selected features J = zeros(m,1); % Jmax = 0; k = 0; if show ff = Bio_statusbar('SFS progress'); end while (k<m) if show ff = Bio_statusbar(k/m,ff); end fnew = 0; Jmax = -Inf; for i=1:N if (k==0) || (sum(selec==i)==0) s = [selec; i]; fs = f(:,s); Js = Bfa_score(fs,d,options); if (Js>=Jmax) ks = i; Jmax = Js; fnew = 1; end end end if (fnew) selec = [selec; ks]; k = k + 1; J(k) = Jmax; if show clf bar(J) fprintf('Jmax = %8.4f\n',Jmax); hold on for i=1:length(selec) text(i-0.4,J(i)*1.05,sprintf('%d',selec(i))); end pause(0) end else disp('Bfs_sfs: no more improvement. Sequential search for feature selection is interrupted.'); if and(force,(k<m)) fprintf('Bfs_sfs: Warning! %d random features were selected in order to have\n',m-k); fprintf(' %d selected features (options.force is true).\n',m); t = 1:N; t(selec) = []; n = length(t); x = rand(n,1); [i,j] = sort(x); selec = [selec; t(j(1:m-k))' ]; end k = 1e10; end end if show delete(ff); end
github
domingomery/Balu-master
Bfs_rank.m
.m
Balu-master/FeatureSelection/Bfs_rank.m
2,709
utf_8
04c850f50a535397c9a1dc6eaaf5ce03
% selec = Bfs_rank(X,d,options)% % % Toolbox: Balu % Feature selection based on command rankfeatures (from MATLAB % Bioinformatics Toolbox) that ranks ranks key features by class % separability criteria. % % input: X feature matrix % options.m number of features to be selected % options.criterion can be: % 'ttest' (default) Absolute value two-sample T-test with pooled % variance estimate % 'entropy' Relative entropy, also known as Kullback-Lieber % distance or divergence % 'brattacharyya' Minimum attainable classification error or % Chernoff bound % 'roc' Area between the empirical receiver operating % characteristic (ROC) curve and the random classifier % slope % 'wilcoxon' Absolute value of the u-statistic of a two-sample % unpaired Wilcoxon test, also known as Mann-Whitney % % Notes: 1) 'ttest', 'entropy', and 'brattacharyya' assume normal % distributed classes while 'roc' and 'wilcoxon' are nonparametric tests, % 2) all tests are feature independent. % % output: selec selected features % % Example: % load datareal % op.m = 10; % 10 features will be selected % op.criterion = 'roc'; % ROC criterion will be used % op.show = 1; % display results % s = Bfs_rank(f,d,op); % index of selected features % X = f(:,s); % selected features % Xn = fn(s,:) % list of feature names % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl % function selec = Bfs_rank(X,d,options) m = options.m; criterion = options.criterion; dmin = min(d); dmax = max(d); k = dmax-dmin+1; if not(exist('criterion','var')) criterion = 'ttest'; end if k<2 error('Bfs_rank: Number of classes of d must be greater than 1.'); end if ~exist('rankfeatures','file') error('Bfs_rank: This function requires Bioinformatics Toolbox.'); end if k==2; idx = rankfeatures(X',d,'criterion',criterion); selec = idx(1:m); else [N,M] = size(X); S = zeros(M,k); for j=1:k dj = (d==j)+1; S(:,j) = rankfeatures(X',dj,'criterion',criterion); end T = S'; idx = T(:); i = 1; selec = zeros(m,1); selec(1) = idx(1); j=2; while i<=m if not(ismember(idx(j),selec)) selec(i) = idx(j); i = i+1; end j = j + 1; end end
github
domingomery/Balu-master
Bfs_lsef.m
.m
Balu-master/FeatureSelection/Bfs_lsef.m
4,224
utf_8
43b4356a3d4d8fcb5317ebef270f1153
% [selec,Y,th] = Bfs_lsef(X,options) % % Toolbox: Balu % Feature Selection using LSE-forward algorithm % % input: X feature matrix % options.m number of features to be selected % optoins.show = 1 displays results % % output: selec selected features % Y is equal to A*th, where A = [X(:,selec) ones(size(X,1),1)] % Y is very similar to PCA. % % The main idea of the algorithms is to evaluate and select feature % subsets based on their capacities to reproduce sample projections on % principal axes: % % Reference: % Mao, K. Identifying critical variables of principal components for % unsupervised feature selection Systems, Man, and Cybernetics, Part B: % Cybernetics, IEEE Transactions on, 2005, 35, 339-344 % % Example 1: using PCA % load datareal % s1 = [279 235 268 230 175 165 207 160 269 157]; %indices using Example % %of Bfs_sfs. % X1 = f(:,s1); % preselected features % Xn1 = fn(s1,:); % op.m = 6; % 5 features will be selected % op.show = 1; % display results % op.pca = 1; % s = Bfs_lsef(X1,d,op); % index of selected features % T1 = X1(:,s); % selected features (transformation % % is avoided) % op.p = []; % ds1 = Bcl_lda(T1,d,T1,op); % p1 = Bev_performance(d,ds1) % performance with lsef % T2 = Bft_pca(X1,op.m); % transformed features using PCA % op.p = []; % ds2 = Bcl_lda(T2,d,T2,op); % p2 = Bev_performance(d,ds2) % performance with PCA % fprintf('Performance with lsef = %5.4f, with PCA = %5.4f\n',p1,p2) % % Example 2: Linear transformation of selected features is similar % to PCA. % load datareal % s1 = [279 235 268 230 175 165 207 160 269 157]; %indices using Example % %of Bfs_sfs. % X1 = f(:,s1); % preselected features % Xn1 = fn(s1,:); % op.m = 6; % 6 features will be selected % op.show = 1; % display results % op.pca = 1; % [s,Y,th] = Bfs_lsef(X1,d,op); % Y is computed as A*th, where % % A = [X1(:,s) ones(size(X1,1),1)] % Yt = Bft_pca(X1,op.m); % PCA analysis % sqdif(Y,Yt) % Y and Yt are very similar. % % See also Bft_lseft, Bft_pca, Bft_plsr. % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function [selec,Y,th] = Bfs_lsef(X,d,options) % d is not used by this algorithm. % the sintaxis "Bfs_fosmod(X,d,options)" is allowed in order to be % similar to other Bfs_ functions. if nargin==2; options = d; end m = options.m; show = options.show; if isfield(options,'pca') pcat = options.pca; else pcat = 0; end [N,n] = size(X); % number of instances (samples), number of features % 1) Initialize S to an empty set % S = []; % 2) Initialize R to the full feature set % R = X; % 3) Perform PCA on complete data: % 4) Calaculate sample projections on the first principal axes with 0.95 % energy if pcat Yt = Bft_pca(X,m); else Yt = Bft_plsr(X,d,m); end Ny = length(Yt(:)); % 5) m iterations for m features p = ones(n,1); % '1' means not selected feature for l=1:m em = Inf*ones(n,1); S = X(:,not(p)); Yss = zeros(N,Ny/N,n); ths = zeros(l+1,Ny/N,n); for j=1:n if p(j) A = [S X(:,j) ones(N,1)]; th = (A'*A)\A'*Yt; ths(:,:,j) = th; Ys = A*th; em(j) = norm(Yt-Ys); Yss(:,:,j) = Ys; end end [emin,js] = min(em); % js is the feature that minimizes Yt-Ys, i.e., % Ys is the best fit of Yt computed as a linear % transformation of [S X(:,js) ones(N,1)] Y = Yss(:,:,js); th = ths(:,:,js); if show fprintf('%2d) selected feature=%4d error=%7.2f%%\n',l,js,emin/Ny*100) end p(js) = 0; end selec = find(p==0);
github
domingomery/Balu-master
Bmv_epidist.m
.m
Balu-master/MultiView/Bmv_epidist.m
1,671
utf_8
23fe88b6fd0a2d7bb2ba85a4e316b8ed
% d = Bmv_epidist(m1,m2,F,method) % % Toolbox: Balu % % Distance from m2 to epipolar line l2 = F*m1 % % d = distance2(m1,m2,F,'method') returns the distance % error. The posible corresponding points are m2 and m1. % F is the fundamental matrix. The distance is calculated % using the following methods: % % method = 'euclidean': uses Euclidean distance from m2 to l=F*m1. % % method = 'sampson': uses Sampson distance. % % If no method is given, 'euclidean' will be assumed as default. % % Both methods can be found in: % % R. Hartley and A. Zisserman. Multiple View Geometry in Computer % Vision. Cambridge University Press, 2000. % % Example: % A = rand(3,4); % Projection matrix for view 1 % B = rand(3,4); % Projection matrix for view 1 % M = [1 2 3 1]'; % 3D point (X=1,Y=2,Z=3) % m1 = A*M;m1 = m1/m1(3); % projection point in view 1 % m2 = B*M;m2 = m2/m2(3); % projection point in view 2 % F = Bmv_fundamental(A,B,'tensor'); % Fundamental matrix using tensors % d = Bmv_epidist(m1,m2,F,'sampson') % sampson distance to epipolar line % % See also Bmv_epiplot. % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function d = Bmv_epidist(m1,m2,F,method) if ~exist('method','var') method = 'euclidean'; end d0 = abs(m2'*F*m1); switch lower(method) case 'sampson' l1 = F*m1; l2 = F'*m2; d = d0/sqrt(l1(1)^2+l1(2)^2+l2(1)^2+l2(2)^2); otherwise % euclidean l = F*m1; d = d0/sqrt(l(1)^2+l(2)^2); end
github
domingomery/Balu-master
Bmv_reco3dna.m
.m
Balu-master/MultiView/Bmv_reco3dna.m
2,239
utf_8
29e34b59c3f3155e8f17b93b6b09344e
% [M,err,ms] = Bmv_reco3dna(m,P) % % Toolbox: Balu % % 3D affine reconstruction from n corresponding points % % It returns a 3D point M that fullfils % the following projective equations: % % m1 = P1*M % m2 = P2*M % : % where mk = m(:,k) are the 2D projection points of 3D point M % in image k; Pk = P(k*3-2:k*3,:) the corresponding 3x4 projection. The % last row of a affine projection matrix must be [0 0 0 1]. factors % lambda k are 1 in affine projections. % % mk and M are given in homogeneous coordinates, i.e., mk % are 3x1 vectors, and M is a 4x1 vector. % % ms is the reprojection of M in each view, ideally ms=m. % err is the reprojection error calculated as norm of ms-m. % The method used in this program is proposed in: % % R. Hartley. A linear method for reconstruction from lines and % points. In 5th International Conference on Computer Vision % (ICCV-95), pages 882-887, Cambridge, MA,1995. % % Example: % M = [1 2 3 1]'; % 3D point (X=1,Y=2,Z=3) % P1 = [rand(2,4);0 0 0 1]; % proyection matrix for view 1 % P2 = [rand(2,4);0 0 0 1]; % proyection matrix for view 2 % P3 = [rand(2,4);0 0 0 1]; % proyection matrix for view 3 % P4 = [rand(2,4);0 0 0 1]; % proyection matrix for view 4 % m1 = P1*M; % proyection point in view 1 % m2 = P2*M; % proyection point in view 2 % m3 = P3*M; % proyection point in view 3 % m4 = P4*M; % proyection point in view 4 % P = [P1;P2;P3;P4]; % all projection matrices % m = [m1 m2 m3 m4]; % all proyection points % [Ms,err,ms] = Bmv_reco3dn(m,P) % 3D reconstruction % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [M,err,ms] = Bmv_reco3dna(m,P) n = size(m,2); % number of images Q = zeros(2*n,3); r = zeros(2*n,1); for k = 1:n p = P(k*3-2:k*3,:); Q(k*2-1:k*2,:) = -p(1:2,1:3); r(k*2-1:k*2,:) = p(1:2,4) - m(1:2,k); end M = [(Q'*Q)\Q'*r; 1]; ms = zeros(3,n); ms(:) = P*M; d = ms(1:2,:)-m(1:2,:); err = sqrt(sum(d.*d,1));
github
domingomery/Balu-master
Bmv_tqsift.m
.m
Balu-master/MultiView/Bmv_tqsift.m
4,170
utf_8
1849d73ac546ca5daf5e04b4877f1f29
% D = Bmv_tqsift(Iq,It,options) % % Toolbox: Balu % % Search of image query (Iq) in target image (It) using SIFT. % % options.q : sliding windows's size in pixels % options.d : sliding step in pixels % options.nkp : minimal number of matching keypoints % options.fast : '1' computes all SIFT keypoints of It at once % '0' computes the SIFT keypoints for each sliding window % options.show : display results % options.roi : region of interest where the matching in target image % will be searched. If roi is not given, it will be % considered that the search are is the whole image It. % % D is the detection map. % % % Example 1: % I = imread('X1.png'); % Iq = I(165:194,80:109); % It = imread('X2.png'); % op.q=30; op.d=5; op.show=1;op.nkp=2;op.fast=1; % D = Bmv_tqsift(Iq,It,op); % figure % Bio_edgeview(It,bwperim(D>18)) % % Example 2: % I = imread('X1.png'); % ix = 315:394; jx=60:139; % m1 = [mean(ix) mean(jx) 1]'; % Iq = I(ix,jx); % It = imread('X2.png'); % figure(1); % imshow(I,[]); % title('Query image: blue box') % hold on; % plot(m1(2),m1(1),'rx') % plot([min(jx) min(jx) max(jx) max(jx) min(jx)],[max(ix) min(ix) min(ix) max(ix) max(ix)]) % figure(2); % imshow(It,[]); % title('Target image') % enterpause % disp('Searching matching region without epiolar restriction...') % op.q=80; op.d=5; op.show=1;op.nkp=3;op.fast=0; % D1 = Bmv_tqsift(Iq,It,op); % figure(3) % Bio_edgeview(It,bwperim(D1>10)) % title('without epiplar line') % enterpause % disp('Searching matching region with epiolar restriction...') % close all % F = Bmv_fundamentalSIFT(I,It); % F matrix estimation % ell = F*m1; % epipolar line % R = Bmv_line2img(ell,size(It)); % op.roi = imdilate(R,ones(20,20)); % D2 = Bmv_tqsift(Iq,It,op); % figure(3) % Bio_edgeview(It,bwperim(D2>10)) % title('with epiplar line') % hold on % Bmv_epiplot(F,m1); % % (c) D.Mery, PUC-DCC, 2011 % http://dmery.ing.puc.cl function D = Bmv_tqsift(Iq,It,options) q = options.q; % sliding windows's size d = options.d; % sliding step nm = options.nkp; % minimal number of matching keypoints show = options.show; [N,M] = size(It); D = zeros(N,M); if ~isfield(options,'roi') Iroi = ones(N,M); else Iroi = options.roi; end q2 = fix(q/2); if show figure(1) clf imshow(Iq,[]) title('Query image'); hold on figure(2) clf imshow(It,[]) title('Target image'); hold on drawnow end if size(It,3)==3 It = single(rgb2gray(It)); else It = single(It); end if size(Iq,3)==3 Iq = single(rgb2gray(Iq)) ; else Iq = single(Iq); end if show disp('Bmv_tqsift: computing SIFT descriptors...'); end [fq, dq] = vl_sift(Iq) ; if ~options.fast for i=1:d:N-q+1 for j=1:d:M-q+1 if Iroi(i+q2,j+q2) Itij = It(i:i+q-1,j:j+q-1); [ftij, dtij] = vl_sift(Itij); matches = vl_ubcmatch(dtij,dq); if length(matches)>nm D(i:i+q-1,j:j+q-1)=D(i:i+q-1,j:j+q-1)+1; if show plot(j+q2,i+q2,'go'); drawnow end end end end end else [ft, dt] = vl_sift(It) ; jt = ft(1,:); it = ft(2,:); for i=1:d:N-q+1 ii = find(and(it>=i,it<i+q)); dti = dt(:,ii); jti = jt(ii); for j=1:d:M-q+1 if Iroi(i+q2,j+q2) dtij = dti(:,and(jti>=j,jti<j+q)); matches = vl_ubcmatch(dtij,dq); if length(matches)>nm D(i:i+q-1,j:j+q-1)=D(i:i+q-1,j:j+q-1)+1; if show plot(j+q2,i+q2,'go'); drawnow end end end end end end
github
domingomery/Balu-master
Bmv_projective2D.m
.m
Balu-master/MultiView/Bmv_projective2D.m
2,069
utf_8
2d4ea0df539208a583752e87f6bec971
% J = Bmv_projective2D(I,H,SJ,show) % % Toolbox: Balu % % 2D proyective transformation. % % J = projective2D(I,H,SJ,show) returns a new image J that is computed % from the 2D projective transformation H of I. % % SJ is [NJ MJ] the size of the transformed image J. The % default of SJ is [NJ,MJ] = size(I). % % show = 1 displays images I and J. % % The coordinates of I are (xp,yp) (from x',y'), and the % coordinates of J are (x,y). The relation between both % coordinate systems is: mp = H*m, where mp = [xp yp 1]' % and m = [x y 1]'. % % R. Hartley and A. Zisserman. Multiple View Geometry in Computer % Vision. Cambridge University Press, 2000. % % Example: % I = rgb2gray(imread('testimg4.jpg')); % original image % s = 7.5; t = pi/4; % scale and orientation % H = [s*cos(t) -s*sin(t) -500 % s*sin(t) s*cos(t) -1750 % 0 0 1]; % similarity matrix % J = Bmv_projective2D(I,H,[600 250],1); % projective transformation % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function [J,R] = Bmv_projective2D(I,H,SJ,show) I = double(I); [NI,MI] = size(I); if ~exist('SJ','var') [NJ,MJ] = size(I); else NJ = SJ(1); MJ = SJ(2); end if ~exist('show','var') show = 0; end if (show) figure(1) imshow(I,[]) title('image original') axis on end J = mean(I(:))*ones(NJ,MJ); R = zeros(NJ,MJ); X = (1:NJ)'*ones(1,MJ); Y = ones(NJ,1)*(1:MJ); x = X(:); y = Y(:); m = [x'; y'; ones(1,NJ*MJ)]; mp = H*m; mp = mp./(ones(3,1)*mp(3,:)); mp = fix(mp + [0.5 0.5 0]'*ones(1,NJ*MJ)); mm = [mp(1:2,:); x'; y']; mm = mm(:,mm(1,:)>0); mm = mm(:,mm(2,:)>0); mm = mm(:,mm(1,:)<=NI); mm = mm(:,mm(2,:)<=MI); xp = mm(1,:); yp = mm(2,:); x = mm(3,:); y = mm(4,:); i = xp + (yp-1)*NI; j = x + (y-1)*NJ; J(j) = I(i); R(j) = 1; if (show) figure(2) imshow(J,[]) axis on title('transformed image') end
github
domingomery/Balu-master
Bmv_guihomography.m
.m
Balu-master/MultiView/Bmv_guihomography.m
12,514
utf_8
e3256a2abe57f425b28ed28cb4c4ba1d
function varargout = Bmv_guihomography(varargin) % BMV_GUIHOMOGRAPHY M-file for Bmv_guihomography.fig % BMV_GUIHOMOGRAPHY, by itself, creates a new BMV_GUIHOMOGRAPHY or raises the existing % singleton*. % % H = BMV_GUIHOMOGRAPHY returns the handle to a new BMV_GUIHOMOGRAPHY or the handle to % the existing singleton*. % % BMV_GUIHOMOGRAPHY('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in BMV_GUIHOMOGRAPHY.M with the given input arguments. % % BMV_GUIHOMOGRAPHY('Property','Value',...) creates a new BMV_GUIHOMOGRAPHY or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before matrixH_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to Bmv_guihomography_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Copyright 2002-2003 The MathWorks, Inc. % Edit the above text to modify the response to help Bmv_guihomography % Last Modified by GUIDE v2.5 10-Nov-2014 09:03:20 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Bmv_guihomography_OpeningFcn, ... 'gui_OutputFcn', @Bmv_guihomography_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before Bmv_guihomography is made visible. function Bmv_guihomography_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to Bmv_guihomography (see VARARGIN) % Choose default command line output for Bmv_guihomography handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes Bmv_guihomography wait for user response (see UIRESUME) % uiwait(handles.figure1); dx = 0; dy = 0; th = 0; u0 = 0; v0 = 0; z = 1; x_p = [92 389 420 14]'; y_p = [57 71 305 278]'; save points dx dy th u0 v0 z x_p y_p % --- Outputs from this function are returned to the command line. function varargout = Bmv_guihomography_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in left. function left_Callback(hObject, eventdata, handles) % hObject handle to left (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points dx = dx-[0 0 -20 20]'; x = x_p+dx; y = y_p+dy; save points u0 v0 z th dx dy x_p y_p hshape(x,y) % --- Executes on button press in right. function right_Callback(hObject, eventdata, handles) % hObject handle to right (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points dx = dx+[0 0 -20 20]'; x = x_p+dx; y = y_p+dy; save points u0 v0 z th dx dy x_p y_p hshape(x,y) % --- Executes on button press in A. function A_Callback(hObject, eventdata, handles) % hObject handle to A (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points dy = dy-[-20 0 0 20]'; x = x_p+dx; y = y_p+dy; save points u0 v0 z th dx dy x_p y_p hshape(x,y) % --- Executes on button press in V. function V_Callback(hObject, eventdata, handles) % hObject handle to V (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points dy = dy-[20 0 0 -20]'; x = x_p+dx; y = y_p+dy; save points u0 v0 z th dx dy x_p y_p hshape(x,y) % --- Executes on button press in points. function points_Callback(hObject, eventdata, handles) % hObject handle to points (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) disp('Select 4 points this way and press <Enter>:') disp(' '); disp(' 1------------4'); disp(' | |'); disp(' | |'); disp(' | |'); disp(' 2------------3'); figure(1) [y_p,x_p] = getpts; dy = 0; dx = 0; th = 0; z = 1; u0 = 0; v0 = 0; save points u0 v0 z th dx dy x_p y_p % --- Executes on button press in Load. function Load_Callback(hObject, eventdata, handles) % hObject handle to Load (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) img_name = input('File name: '); I = imread(img_name); [N,M,P] = size(I); if P==3 I = rgb2gray(I); end if (N>500) I = imresize(I,500/N); end figure(1) imshow(I) title('original image') save I I % --- Executes on button press in rotplus. function rotplus_Callback(hObject, eventdata, handles) % hObject handle to rotplus (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points th = th+pi/40; x = x_p+dx; y = y_p+dy; save points u0 v0 z th dx dy x_p y_p hshape(x,y) function Hc = matrixHxy(x,y,x_p,y_p) m1 = [x(1) x(2) x(3) x(4) y(1) y(2) y(3) y(4) 1 1 1 1 ]; m2 = [x_p(1) x_p(2) x_p(3) x_p(4) y_p(1) y_p(2) y_p(3) y_p(4) 1 1 1 1 ]; Hc = Bmv_homographySVD(m1,m2); function hshape(x,y) load I load points [N,M] = size(I); % A1=[x(1) y(1) 1 0 0 0 -x(1)*x_p(1) -y(1)*x_p(1); % 0 0 0 x(1) y(1) 1 -x(1)*y_p(1) -y(1)*y_p(1)]; % A2=[x(2) y(2) 1 0 0 0 -x(2)*x_p(2) -y(2)*x_p(2); % 0 0 0 x(2) y(2) 1 -x(2)*y_p(2) -y(2)*y_p(2)]; % A3=[x(3) y(3) 1 0 0 0 -x(3)*x_p(3) -y(3)*x_p(3); % 0 0 0 x(3) y(3) 1 -x(3)*y_p(3) -y(3)*y_p(3)]; % A4=[x(4) y(4) 1 0 0 0 -x(4)*x_p(4) -y(4)*x_p(4); % 0 0 0 x(4) y(4) 1 -x(4)*y_p(4) -y(4)*y_p(4)]; % b=[x_p(1) y_p(1) x_p(2) y_p(2) x_p(3) y_p(3) x_p(4) y_p(4)]; % % h=inv([A1;A2;A3;A4])*b'; % % Hc =[h(1) h(2) h(3); h(4) h(5) h(6);h(7) h(8) 1]; % disp('aqui') % m1 = [x(1) x(2) x(3) x(4) % y(1) y(2) y(3) y(4) % 1 1 1 1 ]; % % m2 = [x_p(1) x_p(2) x_p(3) x_p(4) % y_p(1) y_p(2) y_p(3) y_p(4) % 1 1 1 1 ]; Hc = matrixHxy(x,y,x_p,y_p); %Hc = Bmv_homographySVD(m1,m2); Ht = [1 0 -N/2;0 1 -M/2;0 0 1]; Hr = [cos(th) -sin(th) 0 sin(th) cos(th) 0 0 0 1]; Hz = [z 0 u0;0 z v0; 0 0 1]; HH = Hz*Hc*inv(Ht)*Hr*Ht; [N,M] = size(I); J = Bmv_projective2D(I,HH,[N M],0); save J J figure(2) imshow(uint8(J)) title('transformed image') % --- Executes on button press in rotminus. function rotminus_Callback(hObject, eventdata, handles) % hObject handle to rotminus (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points th = th-pi/40; x = x_p+dx; y = y_p+dy; save points u0 v0 z th dx dy x_p y_p hshape(x,y) % --- Executes on button press in Save. function Save_Callback(hObject, eventdata, handles) % hObject handle to Save (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) img_format = input('Image format: '); img_name = input('Image name : '); load J imwrite([img_name '.' img_format],img_format); % --- Executes on button press in zoomplus. function zoomplus_Callback(hObject, eventdata, handles) % hObject handle to zoomplus (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points z = z/1.1; x = x_p+dx; y = y_p+dy; save points u0 v0 z th dx dy x_p y_p hshape(x,y) % --- Executes on button press in zoomminus. function zoomminus_Callback(hObject, eventdata, handles) % hObject handle to zoomminus (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points z = z*1.1; x = x_p+dx; y = y_p+dy; save points u0 v0 z th dx dy x_p y_p hshape(x,y) % --- Executes on button press in shiftleft. function shiftleft_Callback(hObject, eventdata, handles) % hObject handle to shiftleft (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points v0 = v0+50*z; x = x_p+dx; y = y_p+dy; save points u0 v0 z th dx dy x_p y_p hshape(x,y) % --- Executes on button press in shiftdown. function shiftdown_Callback(hObject, eventdata, handles) % hObject handle to shiftdown (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points u0 = u0-50*z; x = x_p+dx; y = y_p+dy; save points u0 v0 z th dx dy x_p y_p hshape(x,y) % --- Executes on button press in shiftright. function shiftright_Callback(hObject, eventdata, handles) % hObject handle to shiftright (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points v0 = v0-50*z; x = x_p+dx; y = y_p+dy; save points u0 v0 z th dx dy x_p y_p hshape(x,y) % --- Executes on button press in shiftup. function shiftup_Callback(hObject, eventdata, handles) % hObject handle to shiftup (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points u0 = u0+50*z; x = x_p+dx; y = y_p+dy; save points u0 v0 z th dx dy x_p y_p hshape(x,y) % --- Executes on button press in Ideal. function Ideal_Callback(hObject, eventdata, handles) % hObject handle to Ideal (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load I load points [N,M] = size(I); x = [1 N N 1]'; y = [1 1 M M]'; % A1=[x(1) y(1) 1 0 0 0 -x(1)*x_p(1) -y(1)*x_p(1); % 0 0 0 x(1) y(1) 1 -x(1)*y_p(1) -y(1)*y_p(1)]; % A2=[x(2) y(2) 1 0 0 0 -x(2)*x_p(2) -y(2)*x_p(2); % 0 0 0 x(2) y(2) 1 -x(2)*y_p(2) -y(2)*y_p(2)]; % A3=[x(3) y(3) 1 0 0 0 -x(3)*x_p(3) -y(3)*x_p(3); % 0 0 0 x(3) y(3) 1 -x(3)*y_p(3) -y(3)*y_p(3)]; % A4=[x(4) y(4) 1 0 0 0 -x(4)*x_p(4) -y(4)*x_p(4); % 0 0 0 x(4) y(4) 1 -x(4)*y_p(4) -y(4)*y_p(4)]; % b=[x_p(1) y_p(1) x_p(2) y_p(2) x_p(3) y_p(3) x_p(4) y_p(4)]; % % h=inv([A1;A2;A3;A4])*b'; % % Hc =[h(1) h(2) h(3); h(4) h(5) h(6);h(7) h(8) 1]; Hc = matrixHxy(x,y,x_p,y_p); % [N,M] = size(I); J = Bmv_projective2D(I,Hc,[N M],0); save J J figure(3) imshow(uint8(J),[]) title('transformed image (ideal)') % --- Executes on button press in Restore. function Restore_Callback(hObject, eventdata, handles) % hObject handle to Restore (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load points dy = 0; dx = 0; th = 0; z = 1; u0 = 0; v0 = 0; x = x_p; y = y_p; save points u0 v0 z th dx dy x_p y_p hshape(x,y)
github
domingomery/Balu-master
Bmv_antisimetric.m
.m
Balu-master/MultiView/Bmv_antisimetric.m
654
utf_8
86236235c55d1fd69c735d673022fa1c
% U = Bmv_antisimetric(u) % % Toolbox: Balu % % Antisimetric matrix % % antisimetric(u) returns the antisimetric matrix of a % a 3x1 vector u. % % U = antisimetric(u) is a 3x3 matrix that % U*v = cross(u,v) where cross(u,v) is the cross % product between u and a 3x1 vector v. % % Example: % u = [1 2 3]' % v = rand(3,1) % w1 = cross(u,v) % U = Bmv_antisimetric(u) % w2 = U*v % w1 must be equal to w2 % % (c) D.Mery, PUC-DCC, 2010 % http://dmery.ing.puc.cl function U = Bmv_antisimetric(u) U = [ 0 -u(3) u(2) u(3) 0 -u(1) -u(2) u(1) 0 ];