Jump to content


Check out our Community Blogs





- - - - -

Human face part detection using MATLAB

Posted by SkHacker, 23 April 2013 · 9358 views

human face detection matlab
Human face part detection using MATLAB Face Detection Matlab Code
The following matlab exampes shows how to implement face detection in matlab.
  • Download source codes from attachment
  • lbp_new
    urns 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% Authors: Marko Heikkil?and Timo Ahonen% Check number of input arguments.error(nargchk(1,5,nargin));image=varargin{1};d_image=double(image);if nargin==1spoints=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1];mapping=0;mode='h';endif (nargin == 2) && (length(varargin{2}) == 1)error('Input arguments');endif (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:neighborsspoints(i,1) = -radius*sin((i-1)*a);spoints(i,2) = radius*cos((i-1)*a);endif(nargin >= 4)mapping=varargin{4};elsemapping=0;endif(nargin >= 5)mode=varargin{5};elsemode='h';endendif (nargin > 1) && (length(varargin{2}) > 1)spoints=varargin{2};if(nargin >= 3)mapping=varargin{3};elsemapping=0;endif(nargin >= 4)mode=varargin{4};elsemode='h';endend% Determine the dimensions of the input image.[ysize xsize] = size(image);neighbors=size(spoints,1);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*bsizexbsizey=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 blockorigy=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 imagefor i = 1:neighborsy = 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 datatypesN = image(ry:ry+dy,rx:rx+dx);D = N >= C;else% Interpolation needed, use double type imagesty = 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 valuesN = 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 definedif length(mapping) > 1bins = max(max(mapping)) + 1;for i = 1:size(result,1)for j = 1:size(result,2)result(i,j) = mapping(result(i,j)+1);endendendif (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);endelse%Otherwise return a matrix of unsigned integersif ((bins-1)<=intmax('uint8'))result=uint8(result);elseif ((bins-1)<=intmax('uint16'))result=uint16(result);elseresult=uint32(result);endendend
  • GetMultiscaleLBP

    function LBPFeature = GetMultiscaleLBP(Image,BlockSize,Rs,Ps,patternMapping,BoundaryFlag)% Author Zhenhua Guo, Lei Zhang and David Zhang% Date June 11, 2010% Version 1.0% Get multiscale LBP histogram% Input Image: Image for extracting features% BlockSize: the size of each block% patternMapping: the mapping of LBP patterns% Rs: the radius of multiscale% Ps: the neighborhoods of multiscale% BoundaryFlag: two kinds of selection on dealing with boundary effectif nargin<2BlockSize = [32,32];endif nargin<3Rs = [4,3,2]; % The radius is from small to bigendif nargin<4Ps = [8,8,8];endif nargin<5for i=1:length(Ps)patternMapping{i} = Getmapping(Ps(i),'u2'); % Get LBP mapping for different radiusesendendfor i=1:length(Ps)patternNum(i) = max(patternMapping{i});endif nargin<6BoundaryFlag = 1; % As the effective size of LBP map is differrent for differernt radiuses, some boundary regions could not provide LBP for big radius.% BoundaryFlag=1 for keeping boundary region, BoundaryFlag=0 for removing boundary regionendBlockNum(1) = size(Image,1)/BlockSize(1);BlockNum(2) = size(Image,2)/BlockSize(2);LBPFeature = [];for m=1:BlockNum(1)for n=1:BlockNum(2)subGray = Image((m-1)*BlockSize(1)+1:m*BlockSize(1),(n-1)*BlockSize(2)+1:n*BlockSize(2));if BoundaryFlag == 1% Get LBP mapping for different radiusesfor j=1:length(Ps)LBPTemp{j} = LBP_new(subGray,Rs(j),Ps(j),patternMapping{j},'x');LBPTemp{j} = double(LBPTemp{j});end% Extend LBP map for big radius, and define the pattern of these boundary pixels% as non-uniform patterns for further processingsize1 = size(LBPTemp{length(Ps)});for j=1:length(Ps)-1size2 = size(LBPTemp{j});size12Diff = (size1-size2)/2;LBPTempNew = LBPTemp{j};LBPTemp{j} = ones(size1)*patternNum(j); % Extend the LBP map and make all pixels as non-uniform patternsLBPTemp{j}(1+size12Diff(1):size1(1)-size12Diff(1),1+size12Diff(2):size1(2)-size12Diff(2)) = LBPTempNew; % Validate the pattern of the central partendelseLBPTemp{1} = LBP_new(subGray,Rs(1),Ps(1),patternMapping{1},'x');LBPTemp{1} = double(LBPTemp{1});size1 = size(LBPTemp{1});% Get LBP mapping for different radiuses and remove boundary regionsfor j=2:length(Ps)LBPTemp{j} = LBP_new(subGray,Rs(j),Ps(j),patternMapping{j},'x');size2 = size(LBPTemp{j});size12Diff = (size2-size1)/2;LBPTemp{j} = LBPTemp{j}(1+size12Diff(1):size2(1)-size12Diff(1),1+size12Diff(2):size2(2)-size12Diff(2));LBPTemp{j} = double(LBPTemp{j});endend% Get Hierachial Multiscale LBP HistogramThreshold = patternNum(1);idxMat = LBPTemp{1}==Threshold;for j=2:length(Ps)LBPTemp{1}(idxMat) = LBPTemp{1}(idxMat)+LBPTemp{j}(idxMat);if j
  • getmapping

    %GETMAPPING returns a mapping table for LBP codes.% MAPPING = GETMAPPING(SAMPLES,MAPPINGTYPE) returns a mapping 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% Authors: Marko Heikkil? and Timo Ahonenmapping = 0:2^samples-1;newMax = 0; %number of patterns in the resulting LBP codeindex = 0;if strcmp(mappingtype,'u2') %Uniform 2newMax = samples*(samples-1) + 3;for i = 0:2^samples-1j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate leftnumt = 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 <= 2mapping(i+1) = index;index = index + 1;elsemapping(i+1) = newMax - 1;endendendif strcmp(mappingtype,'ri') %Rotation invarianttmpMap = zeros(2^samples,1) - 1; % Denis% tmpMap = zeros(2^samples) - 1;for i = 0:2^samples-1rm = i;r = i;for j = 1:samples-1r = bitset(bitshift(r,1,samples),1,bitget(r,samples)); %rotate%leftif r < rmrm = r;endendif tmpMap(rm+1) < 0tmpMap(rm+1) = newMax;newMax = newMax + 1;endmapping(i+1) = tmpMap(rm+1);endendif strcmp(mappingtype,'riu2') %Uniform & Rotation invariantnewMax = samples + 2;for i = 0:2^samples - 1j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate leftnumt = sum(bitget(bitxor(i,j),1:samples));if numt <= 2mapping(i+1) = sum(bitget(i,1:samples));elsemapping(i+1) = samples+1;endendend
  • distMATChiSquare

    % distMATChiSquare computes the dissimilarity between training samples and a test sample% DV = distMATChiSquare(train, test) returns the distance vector between training samples and a test sample.% The input "train" is a n*d matrix, and each row of it represent one% training sample. The "test" is a 1*d vector.% Examples% --------% I1=imread('rice1.png');% I2=imread('rice2.png');% I3=imread('rice3.png');% mapping=getmapping(8,'u2');% M(1,=LBP_new(I1,1,8,mapping);% M(2,=LBP_new(I2,1,8,mapping);% S=LBP_new(I3,1,8,mapping);% DV = distMATChiSquare(M,S);function DV = distMATChiSquare(trains, test)% Version 1.0% Authors: Zhenhua Guo, Lei Zhang and David Zhang% Copyright @ Biometrics Research Centre, the Hong Kong Polytechnic University[train_row, train_col] = size(trains);[test_row, test_col] = size(test);testExtend = repmat(test, train_row, 1);subMatrix = trains-testExtend;subMatrix2 = subMatrix.^2;addMatrix = trains+testExtend;idxZero = find(addMatrix==0);addMatrix(idxZero)=1;DistMat = subMatrix2./addMatrix;DV = sum(DistMat,2);
  • DemoCode

    % Sample codes for PolyU palmprint imagesPs=[8,8,8];Rs=[4,3,2];BlockSize = [16,32];for i=1:length(Ps)patternMapping{i} = Getmapping(Ps(i),'u2');end% Read three imagesGray1 = imread('PolyU001_1.bmp');Gray2 = imread('PolyU001_2.bmp');Gray3 = imread('PolyU002_1.bmp');Gray1 = im2double(Gray1);Gray1 = (Gray1-mean(Gray1())/std(Gray1();Gray2 = im2double(Gray2);Gray2 = (Gray2-mean(Gray2())/std(Gray2();Gray3 = im2double(Gray3);Gray3 = (Gray3-mean(Gray3())/std(Gray3();% Get features for three imagesLBPFeature1 = GetMultiscaleLBP(Gray1,BlockSize,Rs,Ps,patternMapping,0);LBPFeature2 = GetMultiscaleLBP(Gray2,BlockSize,Rs,Ps,patternMapping,0);LBPFeature3 = GetMultiscaleLBP(Gray3,BlockSize,Rs,Ps,patternMapping,0);D12 = distMATChiSquare(LBPFeature1,LBPFeature2)D13 = distMATChiSquare(LBPFeature1,LBPFeature3)D23 = distMATChiSquare(LBPFeature2,LBPFeature3)% Sample codes for AR face imagesPs=[8,8,8];Rs=[4,3,2];BlockSize = [20,26];for i=1:length(Ps)patternMapping{i} = Getmapping(Ps(i),'u2');end% Read three imagesGray1 = imread('AR001-1.tif');Gray2 = imread('AR001-2.tif');Gray3 = imread('AR002-1.tif');Gray1 = im2double(Gray1);Gray1 = (Gray1-mean(Gray1())/std(Gray1();Gray2 = im2double(Gray2);Gray2 = (Gray2-mean(Gray2())/std(Gray2();Gray3 = im2double(Gray3);Gray3 = (Gray3-mean(Gray3())/std(Gray3();% Get features for three imagesLBPFeature1 = GetMultiscaleLBP(Gray1,BlockSize,Rs,Ps,patternMapping,1);LBPFeature2 = GetMultiscaleLBP(Gray2,BlockSize,Rs,Ps,patternMapping,1);LBPFeature3 = GetMultiscaleLBP(Gray3,BlockSize,Rs,Ps,patternMapping,1);D12 = distMATChiSquare(LBPFeature1,LBPFeature2)D13 = distMATChiSquare(LBPFeature1,LBPFeature3)D23 = distMATChiSquare(LBPFeature2,LBPFeature3)
  • TLDA_single

    function Eigenvector = TLDA_single(A,options,Dim)% A image matrix, the size is m*n*N% N denotes the number of images and equals the number of classes% m and n denote the row and column of image, respectively.% options - Struct value in Matlab. The fields in options% that can be set:% k ----determins how to construct the Con_A using the corresponding% image,the default value is 3;% Dim --- The dimensionality of the reduced subspace.[m,n,N] = size(A);Con_A=construct_image(A,options);global_mean = mean(Con_A,3);Gw = zeros(n,n);Gb = zeros(n,n);for i = 1 : Nindex_L = (i-1)*2+1;index_R = 2*i;b = Con_A(:,:,index_R) - Con_A(:,:,index_L);class_mean = mean(Con_A(:,:,index_L:index_R),3);Gw = Gw + b'*b;Gb = Gb + (class_mean - global_mean)'*(class_mean - global_mean);end[Eigenvector, Eigenvalue] = eigs(inv(Gw)*Gb,Dim);
  • readme

    % how to use the codeload demodataoptions.k = 3;% default valueDim=25; % manually set it according to the image you used[Eigenvector] = TLDA_single(tr_dat,options,Dim);for i = 1 : 38A(:,:,i) = tr_dat(:,:,i) * Eigenvector;end
  • construct_image
    function [Con_A]=construct_image(A,options);% A denotes the image matrix, the size is m*n*N% N denotes the number of images% m and n are the row and column of image, respectively.[m,n,N]= size(A);Con_A = zeros(m,n,2*N);for i = 1 : Na = A(:,:,i);[U,D,V] = svd(a);Con_A(:,:,2*i-1) = U(:,1:options.k)*D(1:options.k,1:options.k)*V(:,1:options.k)';Con_A(:,:,2*i) = a;

Attached Files



  • 2



My Picture

Search My Blog

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download