基于肤色的人脸检测matlab代码

合集下载

基于matlab的人脸识别源代码

基于matlab的人脸识别源代码

function varargout = FR_Processed_histogram(varargin) %这种算法是基于直方图处理的方法%The histogram of image is calculated and then bin formation is done on the%basis of mean of successive graylevels frequencies. The training is done on odd images of 40 subjects (200 images out of 400 images)%The results of the implemented algorithm is 99.75 (recognition fails on image number 4 of subject 17)gui_Singleton = 1;gui_State = struct('gui_Name', mfilename, ...'gui_Singleton', gui_Singleton, ...'gui_OpeningFcn', @FR_Processed_histogram_OpeningFcn.,..'gui_OutputFcn',@FR_Processed_histogram_OutputFcn.,..'gui_LayoutFcn', [] , ... 'gui_Callback', []);if nargin && ischar(varargin{1}) gui_State.gui_Callback =str2func(varargin{1});endif nargout[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});elsegui_mainfcn(gui_State, varargin{:});end% End initialization code - DO NOT EDIT% -------------------------------------------------------------------------% --- Executes just before FR_Processed_histogram is made visible. function FR_Processed_histogram_OpeningFcn(hObjecte, ventdata, 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 FR_Processed_histogram (see VARARGIN)% Choose default command line output forFR_Processed_histogramhandles.output = hObject;% Update handles structure guidata(hObject, handles);% UIWAIT makes FR_Processed_histogram wait for user response(see UIRESUME)% uiwait(handles.figure1);global total_sub train_img sub_img max_hist_level bin_numform_bin_num;total_sub = 40;train_img = 200;sub_img = 10;max_hist_level = 256;bin_num = 9;form_bin_num = 29;% -------------------------------------------------------------------------% --- Outputs from this function are returned to the command line.function varargout = FR_Processed_histogram_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 structurevarargout{1} = handles.output;% -------------------------------------------------------------------------% --- Executes on button press in train_button.function train_button_Callback(hObject, eventdata, handles)% hObject handle to train_button (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)global train_processed_bin;global total_sub train_img sub_img max_hist_level bin_numform_bin_num;train_processed_bin(form_bin_num,train_img) = 0;K = 1;train_hist_img = zeros(max_hist_level, train_img);for Z=1:1:total_subfor X=1:2:sub_img %%%train on odd number of images of each subjectI = imread( strcat('ORL\S',int2str(Z), '\',int2str(X), '.bmp') ); [rowscols] = size(I);for i=1:1:rowsfor j=1:1:colsif( I(i,j) == 0 ) train_hist_img(max_hist_level, K)train_hist_img(max_hist_level, K) + 1;else train_hist_img(I(i,j), K) = train_hist_img(I(i,j), K) + 1;endendendK = K + 1;endend[r c] = size(train_hist_img);sum = 0;for i=1:1:cK = 1;for j=1:1:rif( (mod(j,bin_num)) == 0 )sum = sum + train_hist_img(j,i);train_processed_bin(K,i) = sum/bin_num; K = K + 1;sum = 0;elsesum = sum + train_hist_img(j,i);endendtrain_processed_bin(K,i) = sum/bin_num;enddisplay ('Training Done') save'train' train_processed_bin;% --- Executes on button press in Testing_button.function Testing_button_Callback(hObject, eventdata, handles)% hObject handle to Testing_button (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global train_img max_hist_level bin_num form_bin_num;global train_processed_bin;global filename pathname Iload 'train'test_hist_img(max_hist_level) = 0;test_processed_bin(form_bin_num) = 0;[rows cols] = size(I);for i=1:1:rowsfor j=1:1:colsif( I(i,j) == 0 )test_hist_img(max_hist_level)test_hist_img(max_hist_level) + 1;elsetest_hist_img(I(i,j)) = test_hist_img(I(i,j)) + 1;endendend[r c] = size(test_hist_img); sum = 0;K = 1;for j=1:1:cif( (mod(j,bin_num)) == 0 )sum = sum + test_hist_img(j); test_processed_bin(K) =sum/bin_num;K = K + 1;sum = 0;elsesum = sum + test_hist_img(j);endendtest_processed_bin(K) = sum/bin_num;sum = 0;K = 1;for y=1:1:train_imgfor z=1:1:form_bin_numsum = sum + abs( test_processed_bin(z) - train_processed_bin(z,y) );endimg_bin_hist_sum(K,1) = sum;sum = 0;K = K + 1;end[temp M] = min(img_bin_hist_sum);M = ceil(M/5);getString_start=strfind(pathname',S');getString_start=getString_start(end)+1;getString_end=strfind(pathname',\');getString_end=getString_end(end)-1;subjectindex=str2num(pathname(getString_start:getString_end));if (subjectindex == M)axes (handles.axes3)%image no: 5 is shown for visualization purposeimshow(imread(STRCAT('ORL\S',num2str(M),'\5.bmp')))msgbox ( 'Correctly Recognized');elsedisplay ([ 'Error==> Testing Image of Subject >>'num2str(subjectindex) ' matches with the image of subject >> 'num2str(M)])axes (handles.axes3)%image no: 5 is shown for visualization purposeimshow(imread(STRCAT( 'ORL\S' ,num2str(M),'\5.bmp')))msgbox ( 'Incorrectly Recognized');enddisplay('Testing Done')% -------------------------------------------------------------------------function box_Callback(hObject, eventdata, handles)% hObject handle to box (see GCBO)% eventdata reserved - to be defined in a future version ofMATLAB% handles structure with handles and user data (see GUIDATA)% Hints: get(hObject,'String') returns contents of box as text% str2double(get(hObject,'String')) returns contents of box as a double% -------------------------------------------------------------------------% --- Executes during object creation, after setting all properties.function box_CreateFcn(hObject, eventdata, handles)% hObject handle to box (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called% Hint: edit controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');end% --- Executes on button press in Input_Image_button.function Input_Image_button_Callback(hObject, eventdata, handles) % hObject handle to Input_Image_button (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global filename pathname I[filename, pathname] = uigetfile('*.bmp', 'Test Image');axes(handles.axes1)imgpath=STRCAT(pathname,filename);I = imread(imgpath);imshow(I)% -------------------------------------------------------------------------% --- Executes during object creation, after setting all properties.function axes3_CreateFcn(hObject, eventdata, handles)% hObject handle to axes3 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called% Hint: place code in OpeningFcn to populate axes3%Programmed by Usman Qayyum。

基于肤色的人脸检测matlab代码

基于肤色的人脸检测matlab代码

基于肤色的人脸检测matlab代码mainclose allclear allclc% 输入图像名字img_name = input('请输入图像名字(图像必须为RGB图像,输入0结束):','s'); % 当输入0时结束while ~strcmp(img_name,'0')% 进行人脸识别facedetection(img_name);img_name = input('请输入图像名字(图像必须为RGB图像,输入0结束):','s'); endfacedetectionfunctionfacedetection(img_name)% 读取RGB图像I = imread(img_name);% 转换为灰度图像gray = rgb2gray(I);% 将图像转化为YCbCr颜色空间YCbCr = rgb2ycbcr(I);% 获得图像宽度和高度heigth = size(gray,1);width = size(gray,2);% 根据肤色模型将图像二值化fori = 1:heigthfor j = 1:widthY = YCbCr(i,j,1);Cb = YCbCr(i,j,2);Cr = YCbCr(i,j,3);if(Y < 80)gray(i,j) = 0;elseif(skin(Y,Cb,Cr) == 1)gray(i,j) = 255;elsegray(i,j) = 0;endendendend% 二值图像形态学处理SE=strel('arbitrary',eye(5));%gray = bwmorph(gray,'erode');% imopen先腐蚀再膨胀gray = imopen(gray,SE);% imclose先膨胀再腐蚀%gray = imclose(gray,SE);imshow(gray);% 取出图片中所有包含白色区域的最小矩形[L,num] = bwlabel(gray,8);STATS = regionprops(L,'BoundingBox'); % 存放经过筛选以后得到的所有矩形块n = 1;result = zeros(n,4);figure,imshow(I);hold on;fori = 1:numbox = STATS(i).BoundingBox;x = box(1); %矩形坐标xy = box(2); %矩形坐标yw = box(3); %矩形宽度wh = box(4); %矩形高度h% 宽度和高度的比例ratio = h/w;ux = uint8(x);uy = uint8(y);ifux> 1ux = ux - 1;endifuy> 1uy = uy - 1;end% 可能是人脸区域的矩形应满足以下条件:% 1、高度和宽度必须都大于20,且矩形面积大于400 % 2、高度和宽度比率应该在范围(0.6,2)内% 3、函数findeye返回值为1if w < 20 || h < 20 || w*h < 400continueelseif ratio < 2 && ratio > 0.6 &&findeye(gray,ux,uy,w,h) == 1 % 记录可能为人脸的矩形区域result(n,:) = [uxuy w h];n = n+1;endend% 对可能是人脸的区域进行标记if size(result,1) == 1 && result(1,1) > 0rectangle('Position',[result(1,1),result(1,2),result(1,3),result(1, 4)],'EdgeColor','r'); else% 如果满足条件的矩形区域大于1则再根据其他信息进行筛选for m = 1:size(result,1)m1 = result(m,1);m2 = result(m,2);m3 = result(m,3);m4 = result(m,4);% 标记最终的人脸区域if m1 + m3 < width && m2 + m4 <heigth< p=""> rectangle('Position',[m1,m2,m3,m4],'EdgeColor','r');endendendfindeye% 判断二值图像中是否含有可能是眼睛的块% bImage----二值图像% x---------矩形左上角顶点X坐标% y---------矩形左上角顶点Y坐标% w---------矩形宽度% h---------矩形长度% 如果有则返回值eye等于1,否则为0function eye = findeye(bImage,x,y,w,h)% 根据矩形相关属性得到二值图像中矩形区域中的数据% 存放矩形区域二值图像信息part = zeros(h,w);% 二值化fori = y:(y+h)for j = x:(x+w)ifbImage(i,j) == 0part(i-y+1,j-x+1) = 255;elsepart(i-y+1,j-x+1) = 0;endendend[L,num] = bwlabel(part,8);% 如果区域中有两个以上的矩形则认为有眼睛ifnum< 2eye = 0;elseeye = 1;endskin% Anil K.Jain提出的基于YCbCr颜色空间的肤色模型% 根据当前点的Cb Cr值判断是否为肤色function result = skin(Y,Cb,Cr)% 参数% a = 25.39;a = 28;% b = 14.03;b=18;ecx = 1.60;ecy = 2.41;sita = 2.53;cx = 109.38;cy = 152.02;xishu = [cos(sita) sin(sita);-sin(sita) cos(sita)];% 如果亮度大于230,则将长短轴同时扩大为原来的1.1倍if(Y > 230)a = 1.1*a;b = 1.1*b;end% 根据公式进行计算Cb = double(Cb);Cr = double(Cr);t = [(Cb-cx);(Cr-cy)];temp = xishu*t;value = (temp(1) - ecx)^2/a^2 + (temp(2) - ecy)^2/b^2; % 大于1则不是肤色,返回0;否则为肤色,返回1if value > 1result = 0;elseresult = 1;end</heigth<>。

基于matlab的人脸识别源代码

基于matlab的人脸识别源代码

function varargout = FR_Processed_histogram(varargin) %这种算法是基于直方图处理的方法%The histogram of image is calculated and then bin formation is done on the%basis of mean of successive graylevels frequencies. The training is done on odd images of 40 subjects (200 images out of 400 images)%The results of the implemented algorithm is 99.75 (recognition fails on image number 4 of subject 17)gui_Singleton = 1;gui_State = struct('gui_Name', mfilename, ...'gui_Singleton', gui_Singleton, ...'gui_OpeningFcn', @FR_Processed_histogram_OpeningFcn.,..'gui_OutputFcn',@FR_Processed_histogram_OutputFcn.,..'gui_LayoutFcn', [] , ... 'gui_Callback', []);if nargin && ischar(varargin{1}) gui_State.gui_Callback =str2func(varargin{1});endif nargout[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});elsegui_mainfcn(gui_State, varargin{:});end% End initialization code - DO NOT EDIT% -------------------------------------------------------------------------% --- Executes just before FR_Processed_histogram is made visible. function FR_Processed_histogram_OpeningFcn(hObjecte, ventdata, 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 FR_Processed_histogram (see VARARGIN)% Choose default command line output forFR_Processed_histogramhandles.output = hObject;% Update handles structure guidata(hObject, handles);% UIWAIT makes FR_Processed_histogram wait for user response(see UIRESUME)% uiwait(handles.figure1);global total_sub train_img sub_img max_hist_level bin_numform_bin_num;total_sub = 40;train_img = 200;sub_img = 10;max_hist_level = 256;bin_num = 9;form_bin_num = 29;% -------------------------------------------------------------------------% --- Outputs from this function are returned to the command line.function varargout = FR_Processed_histogram_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 structurevarargout{1} = handles.output;% -------------------------------------------------------------------------% --- Executes on button press in train_button.function train_button_Callback(hObject, eventdata, handles)% hObject handle to train_button (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)global train_processed_bin;global total_sub train_img sub_img max_hist_level bin_numform_bin_num;train_processed_bin(form_bin_num,train_img) = 0;K = 1;train_hist_img = zeros(max_hist_level, train_img);for Z=1:1:total_subfor X=1:2:sub_img %%%train on odd number of images of each subjectI = imread( strcat('ORL\S',int2str(Z), '\',int2str(X), '.bmp') ); [rowscols] = size(I);for i=1:1:rowsfor j=1:1:colsif( I(i,j) == 0 ) train_hist_img(max_hist_level, K)train_hist_img(max_hist_level, K) + 1;else train_hist_img(I(i,j), K) = train_hist_img(I(i,j), K) + 1;endendendK = K + 1;endend[r c] = size(train_hist_img);sum = 0;for i=1:1:cK = 1;for j=1:1:rif( (mod(j,bin_num)) == 0 )sum = sum + train_hist_img(j,i);train_processed_bin(K,i) = sum/bin_num; K = K + 1;sum = 0;elsesum = sum + train_hist_img(j,i);endendtrain_processed_bin(K,i) = sum/bin_num;enddisplay ('Training Done') save'train' train_processed_bin;% --- Executes on button press in Testing_button.function Testing_button_Callback(hObject, eventdata, handles)% hObject handle to Testing_button (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global train_img max_hist_level bin_num form_bin_num;global train_processed_bin;global filename pathname Iload 'train'test_hist_img(max_hist_level) = 0;test_processed_bin(form_bin_num) = 0;[rows cols] = size(I);for i=1:1:rowsfor j=1:1:colsif( I(i,j) == 0 )test_hist_img(max_hist_level)test_hist_img(max_hist_level) + 1;elsetest_hist_img(I(i,j)) = test_hist_img(I(i,j)) + 1;endendend[r c] = size(test_hist_img); sum = 0;K = 1;for j=1:1:cif( (mod(j,bin_num)) == 0 )sum = sum + test_hist_img(j); test_processed_bin(K) =sum/bin_num;K = K + 1;sum = 0;elsesum = sum + test_hist_img(j);endendtest_processed_bin(K) = sum/bin_num;sum = 0;K = 1;for y=1:1:train_imgfor z=1:1:form_bin_numsum = sum + abs( test_processed_bin(z) - train_processed_bin(z,y) );endimg_bin_hist_sum(K,1) = sum;sum = 0;K = K + 1;end[temp M] = min(img_bin_hist_sum);M = ceil(M/5);getString_start=strfind(pathname',S');getString_start=getString_start(end)+1;getString_end=strfind(pathname',\');getString_end=getString_end(end)-1;subjectindex=str2num(pathname(getString_start:getString_end));if (subjectindex == M)axes (handles.axes3)%image no: 5 is shown for visualization purposeimshow(imread(STRCAT('ORL\S',num2str(M),'\5.bmp')))msgbox ( 'Correctly Recognized');elsedisplay ([ 'Error==> Testing Image of Subject >>'num2str(subjectindex) ' matches with the image of subject >> 'num2str(M)])axes (handles.axes3)%image no: 5 is shown for visualization purposeimshow(imread(STRCAT( 'ORL\S' ,num2str(M),'\5.bmp')))msgbox ( 'Incorrectly Recognized');enddisplay('Testing Done')% -------------------------------------------------------------------------function box_Callback(hObject, eventdata, handles)% hObject handle to box (see GCBO)% eventdata reserved - to be defined in a future version ofMATLAB% handles structure with handles and user data (see GUIDATA)% Hints: get(hObject,'String') returns contents of box as text% str2double(get(hObject,'String')) returns contents of box as a double% -------------------------------------------------------------------------% --- Executes during object creation, after setting all properties.function box_CreateFcn(hObject, eventdata, handles)% hObject handle to box (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called% Hint: edit controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');end% --- Executes on button press in Input_Image_button.function Input_Image_button_Callback(hObject, eventdata, handles) % hObject handle to Input_Image_button (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global filename pathname I[filename, pathname] = uigetfile('*.bmp', 'Test Image');axes(handles.axes1)imgpath=STRCAT(pathname,filename);I = imread(imgpath);imshow(I)% -------------------------------------------------------------------------% --- Executes during object creation, after setting all properties.function axes3_CreateFcn(hObject, eventdata, handles)% hObject handle to axes3 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles empty - handles not created until after all CreateFcns called% Hint: place code in OpeningFcn to populate axes3%Programmed by Usman Qayyum。

基于matlab的人脸检测程序

基于matlab的人脸检测程序

基于Matlab的一个最简单的人脸检测程序2010-08-09 20:28:39| 分类:默认分类| 标签:matlab 人脸检测程序|字号大中小订阅clear;I=imread('E:\Matlab\图片\q5.jpg');O=rgb2ntsc(I);G=O(:,:,2);[m n]=size(G);U=zeros(m,n);for i=1:mfor j=1:nif G(i,j)>0.03&&G(i,j)<0.16U(i,j)=1;endendendsr=strel('disk',6);C=imclose(U,sr);L=bwlabel(C);B=regionprops(L,'area');Se=[B.Area];Sm=max(Se);if Sm>m*n/27B1=bwareaopen(C,Sm);k_y1=m;k2=m;l2=n;if any(B1(i,:))==1k_y1=i;breakendendfor i=k_y1:mif B1(i,:)==0k2=i;breakendendfor j=1:nif any(B1(:,j))==1l_y1=j;breakendendfor j=l_y1:nif B1(:,j)==0l2=j;breakendendk_y=k2-k_y1;if k_y>.5*l&&k_y<3*lI1=imcrop(B1,[l_y1 k_y1 l .4*k_y]); [n1 m1]=size(I1);L1=bwlabel(I1);E=regionprops(L1,'area');Si=[E.Area];Sm=max(Si);if Sm/(n1*m1)>.3B2=bwareaopen(I1,floor(.5*Sm)); g_y1=m1;g2=m1;for j=1:m1if any(B2(:,j))==1g_y1=j;breakendendfor j=g_y1:m1if B2(:,j)==0;g2=j;breakendendg=g2-g_y1;figure;imshow(I);hold onh1=line([l_y1+g_y1,l_y1+g_y1+g],[k_y1,k_y1]);h2=line([l_y1+g_y1+g,l_y1+g_y1+g],[k_y1,k_y1+1.1*g]);h3=line([l_y1+g_y1+g,l_y1+g_y1],[k_y1+1.1*g,k_y1+1.1*g]);h4=line([l_y1+g_y1,l_y1+g_y1],[k_y1+1.1*g,k_y1]);h=[h1 h2 h3 h4];set(h,'Color',[1 0 0],'LineWidth',2);elsefigure;imshow(I);endelsefigure;imshow(I);endelsefigure;imshow(I);end注:本程序是基于肤色的人脸侦测程序,较为简单,只能检测出一个人脸,对于背景较单调的情况下的个体照,有较高的检测率,而且检测速度快。

matlab编程--基于肤色分割和匹配的人脸识别介绍

matlab编程--基于肤色分割和匹配的人脸识别介绍

基于肤色分割和匹配的人脸识别1.将RGB空间转换为YCbCr空间:为了把人脸区域从非人脸区域分割出来,需要使用适合不同肤色和不同光照条件的可靠的肤色模型。

常用的RGB 表示方法不适合于皮肤模型,在RGB 空间,三基色(r、g、b)不仅代表颜色,还表示了亮度。

由于周围环境光照的改变,亮度可能使人脸的检测变得更加复杂,在皮肤的分割过程中是不可靠的。

为利用肤色在色度空间的聚类性,需要把颜色表达式中的色度信息与亮度信息分开,将R、G、B 转换为色度与亮度分开的色彩表达空间可以达到这个目的。

颜色空间的转换常用的颜色模型主要有:YCrCb、HSV、YIQ等。

在本文的实验中选用YCrCb 空间作为肤色分布统计的映射空间,该空间的优点是受亮度变化的影响较小,而且是两维独立分布,能较好地限制肤色分布区域。

使用函数为:YCBCR = rgb2ycbcr(RGB);2.将彩色图像转换为灰度图像,实验证明,不同的肤色具有相同的2D模型G(m,V^2)。

灰度值对应属于皮肤区域的可能性,同过设定门限,就可以转换为二值图像,1,0分别表示皮肤和非皮肤区域。

皮肤颜色在ycbcr色度空间的分布范围为:100<=cb<=127,138<=cr<=170,可以将彩色图像转换为二值图像:f_cb=f(:,:,2);f_cr=f(:,:,3);f = (f_cb>=100) & (f_cb<=127) & (f_cr>=138) &(f_cr<=170) ;figure; imshow(f);3.转换后不可避免出现了噪声,有背景的噪声影响,以及人的衣服和裤子引起的噪声点,使用开闭运算的方法消除噪声:se=strel('square',3);f=imopen(f,se);f=imclose(f,se);figure(2),imshow(f);4.对图像做填孔处理f=imfill(f,'holes');figure(3),imshow(f);5.对图像进行重构,即利用重构进行开运算,可准确恢复腐蚀后的对象形状. fe=imerode(f,ones(8,7));fo=imopen(f,ones(8,7));f=imreconstruct(fe,f);figure(4),imshow(f);6.相关匹配,实际作用效果不大,可以注释掉. %w=ones(3);%f=imfilter(f,w);%figure(5),imshow(f);% [M,N]=size(f);% f=fft2(f);% w=conj(fft2(w,M,N));% g=real(ifft2(w.*f));% gs=gscale(g);% figure,imshow(gs);7.人脸候选区筛选时,由于头部部分重合,以及头部与其他部分,例如衣服等的连接,对筛选造成了困难,故应先利用闭运算操作,断开连接,再进行处理.se1=strel('square',8);f=imerode(f,se1);f=imdilate(f,se1);figure(6),imshow(f);8. 利用人脸候选区筛选,进一步确定人脸区域(判断规则如下):(1)若目标高宽比小于0.8而大于2.0,则认为不是人脸区域,删除此区域。

matlab编程--基于肤色分割和匹配的人脸识别介绍

matlab编程--基于肤色分割和匹配的人脸识别介绍

基于肤色分割和匹配的人脸识别1.将RGB空间转换为YCbCr空间:为了把人脸区域从非人脸区域分割出来,需要使用适合不同肤色和不同光照条件的可靠的肤色模型。

常用的RGB 表示方法不适合于皮肤模型,在RGB 空间,三基色(r、g、b)不仅代表颜色,还表示了亮度。

由于周围环境光照的改变,亮度可能使人脸的检测变得更加复杂,在皮肤的分割过程中是不可靠的。

为利用肤色在色度空间的聚类性,需要把颜色表达式中的色度信息与亮度信息分开,将R、G、B 转换为色度与亮度分开的色彩表达空间可以达到这个目的。

颜色空间的转换常用的颜色模型主要有:YCrCb、HSV、YIQ等。

在本文的实验中选用YCrCb 空间作为肤色分布统计的映射空间,该空间的优点是受亮度变化的影响较小,而且是两维独立分布,能较好地限制肤色分布区域。

使用函数为:YCBCR = rgb2ycbcr(RGB);2.将彩色图像转换为灰度图像,实验证明,不同的肤色具有相同的2D模型G(m,V^2)。

灰度值对应属于皮肤区域的可能性,同过设定门限,就可以转换为二值图像,1,0分别表示皮肤和非皮肤区域。

皮肤颜色在ycbcr色度空间的分布范围为:100<=cb<=127,138<=cr<=170,可以将彩色图像转换为二值图像:f_cb=f(:,:,2);f_cr=f(:,:,3);f = (f_cb>=100) & (f_cb<=127) & (f_cr>=138) &(f_cr<=170) ;figure; imshow(f);3.转换后不可避免出现了噪声,有背景的噪声影响,以及人的衣服和裤子引起的噪声点,使用开闭运算的方法消除噪声:se=strel('square',3);f=imopen(f,se);f=imclose(f,se);figure(2),imshow(f);4.对图像做填孔处理f=imfill(f,'holes');figure(3),imshow(f);5.对图像进行重构,即利用重构进行开运算,可准确恢复腐蚀后的对象形状. fe=imerode(f,ones(8,7));fo=imopen(f,ones(8,7));f=imreconstruct(fe,f);figure(4),imshow(f);6.相关匹配,实际作用效果不大,可以注释掉. %w=ones(3);%f=imfilter(f,w);%figure(5),imshow(f);% [M,N]=size(f);% f=fft2(f);% w=conj(fft2(w,M,N));% g=real(ifft2(w.*f));% gs=gscale(g);% figure,imshow(gs);7.人脸候选区筛选时,由于头部部分重合,以及头部与其他部分,例如衣服等的连接,对筛选造成了困难,故应先利用闭运算操作,断开连接,再进行处理.se1=strel('square',8);f=imerode(f,se1);f=imdilate(f,se1);figure(6),imshow(f);8. 利用人脸候选区筛选,进一步确定人脸区域(判断规则如下):(1)若目标高宽比小于0.8而大于 2.0,则认为不是人脸区域,删除此区域。

基于MATLAB的人脸识别源程序

基于MATLAB的人脸识别源程序

基于MATLA酌人脸识别源程序1•色彩空间转换function [r,g]=rgb_RGB(Ori_Face)R=0ri_Face(:,:,1);G=0ri_Face(:,:,2);B=Ori_Face(:,:,3);R1=im2double(R); % 将uint8 型转换成double型G1=im2double(G);B1=im2double(B);RGB=R1+G1+B1;row=size(Ori_Face, 1); %行像素column=size(Ori_Face,2); %列像素for i=1:rowfor j=1:columnrr(i,j)=R1(i,j)/RGB(i,j);gg(i,j)=G1(i,j)/RGB(i,j);endendrrr=mean(rr);r=mean(rrr);ggg=mean(gg);g=mean(ggg); 2•均值和协方差皮肤库\2・jpg');[r2,g2]=rgb_RGB(t2);皮肤库\3・jpg');[r3,g3]=rgb_RGB(t3);皮肤库\4・jpg');[r4,g4]=rgb_RGB(t4);皮肤库\5・jpg');[r5,g5]=rgb_RGB(t5);皮肤库\6・jpg');[r6,g6]=rgb_RGB(t6);皮肤库\7・jpg');[r7,g7]=rgb_RGB(t7);皮肤库\8・jpg');[r8,g8]=rgb_RGB(t8);皮肤库\9・jpg');[r9,g9]=rgb_RGB(t9);皮肤库\10・jpg');[r10,g10]=rgb_RGB(t10); 皮肤库\11・jpg');[r11,g11]=rgb_RGB(t11); 皮肤库\12・jpg');[r12,g12]=rgb_RGB(t12); 皮肤库\13・jpg');[r13,g13]=rgb_RGB(t13); 皮肤库\14・jpg');[r14,g14]=rgb_RGB(t14); 皮肤库\15・jpg');[r15,g15]=rgb_RGB(t15); 皮肤库\16・jpg');[r16,g16]=rgb_RGB(t16); 皮肤库\17・jpg');[r17,g17]=rgb_RGB(t17); 皮肤库\18・jpg');[r18,g18]=rgb_RGB(t18); 皮肤库\19・jpg');[r19,g19]=rgb_RGB(t19); 皮肤库\20・jpg');[r20,g20]=rgb_RGB(t20); 皮肤库\21・jpg');[r21,g21]=rgb_RGB(t21);皮肤库\24・jpg');[r24,g24]=rgb_RGB(t24);皮肤库\25・jpg');[r25,g25]=rgb_RGB(t25);皮肤库\26・jpg');[r26,g26]=rgb_RGB(t26);皮肤库\27・jpg');[r27,g27]=rgb_RGB(t27); r=cat(1,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16,r17,r18, r19,r20,r21,r22,r23,r24,r25,r26,r27);g=cat(1,g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11,g12,g13,g14,g15,g16,g17,g1 8,g19,g20,g21,g22,g23,g24,g25,g26,g27);m=mean([r,g])n=cov([r,g])3•求质心function [xmean, ymean] = center(bw)bw=bwfill(bw,'holes');area = bwarea(bw);[m n] =size(bw);bw=double(bw);xmean =0; ymean = 0;for i=1:m,for j=1:n,xmean = xmean + j*bw(i,j);ymean = ymean + i*bw(i,j);end;end;if(area==0)xmean=0;ymean=0;elsexmean = xmean/area;ymean = ymean/area;xmean = round(xmean);ymean = round(ymean);end4.求偏转角度function [theta] = orient(bw,xmean,ymean) [m n] =size(bw); bw=double(bw);a = 0;b = 0;c = 0;for i=1:m,for j=1:n,a = a + (j - xmean)A2 * bw(i,j);b = b + (j - xmean) * (i - ymean) * bw(i,j);c = c + (i - ymean)A2 * bw(i,j);end;end;b = 2 * b;theta = atan(b/(a-c))/2;theta = theta*(180/pi); % 从幅度转换到角度5.找区域边界function [left, right, up, down] = bianjie(A)[m n] = size(A);left = -1;right = -1;up = -1;down = -1;for j=1:n,for i=1:m,if (A(i,j) ~= 0)left = j;break;end;end;if (left ~= -1) break;end;end;for j=n:-1:1,for i=1:m,if (A(i,j) ~= 0)right = j;break;end;end;if (right ~= -1) break; end;end;for i=1:m,for j=1:n,if (A(i,j) ~= 0)up = i;break;end;end;if (up ~= -1) break;end;end;for i=m:-1:1,for j=1:n,if (A(i,j) ~= 0)down = i;break;end;end;if (down ~= -1)break;end;end;6.求起始坐标function newcoord = checklimit(coord,maxval)newcoord = coord;if (newcoord<1)newcoord=1;end;if (newcoord>maxval)newcoord=maxval;end;7•模板匹配function [ccorr, mfit, RectCoord]mobanpipei(mult. frontalmodel,ly,wx,cx, cy, angle) frontalmodel=rgb2gray(frontalmodel);model_rot = imresize(frontalmodel,[ly wx],'bilinear'); % 调整模板大小model_rot = imrotate(model_rot,angle,'bilinear'); %旋转模板[l,r,u,d] = bianjie(model_rot); % 求边界坐标bwmodel_rot=imcrop(model_rot,[l u (r-l) (d-u)]); % 选择模板人脸区域[modx,mody] =center(bwmodel_rot); % 求质心[morig, norig] = size(bwmodel_rot);%产生一个覆盖了人脸模板的灰度图像mfit = zeros(size(mult));mfitbw = zeros(size(mult));[limy, limx] = size(mfit);%计算原图像中人脸模板的坐标startx = cx-modx;starty = cy-mody;endx = startx + norig-1;endy = starty + morig-1;startx = checklimit(startx,limx);starty = checklimit(starty,limy);endx = checklimit(endx,limx);endy = checklimit(endy,limy);for i=starty:endy,for j=startx:endx,mfit(i,j) = model_rot(i-starty+1,j-startx+1);end;end;ccorr = corr2(mfit,mult) % 计算相关度[l,r,u,d] = bianjie(bwmodel_rot);sx = startx+l;sy = starty+u;RectCoord = [sx sy (r-1) (d-u)]; % 产生矩形坐标8.主程序clear;[fname,pname]=uigetfile({'*・jpg';'* .bmp';'* ・tif';'* ・gif'},'Please choose a color picture・・・');%返回打开的图片名与图片路径名[u,v]=size(fname);y=fname(v); % 图片格式代表值switch ycase 0errordlg('You Should Load Image File First ・・・','Warning ・・・');case{'g';'G';'p';'P';'f';'F'}; % 图片格式若是JPG/jpg、BMP/bmp、TIF/tif 或者GIF/gif,才打开I=cat(2,pname,fname);Ori_Face=imread(l);subplot(2,3,1),imshow(Ori_Face);otherwiseerrordlg('You Should Load Image File First ・・・','Warning ・・・'); endR=Ori_Face(:,:,1);G=Ori_Face(:,:,2);B=Ori_Face(:,:,3);R1=im2double(R); % 将uint8 型转换成double型处理G1=im2double(G);B1=im2double(B);RGB=R1+G1+B1;m=[ 0・4144,0.3174]; % 均值n=[0・0031,-0・0004;-0・0004,0.0003]; % 方差row=size(Ori_Face,1); % 行像素数column=size(Ori_Face,2); % 列像素数for i=1:rowfor j=1:columnif RGB(i,j)==0rr(i,j)=0;gg(i,j)=0;elserr(i,j)=R1(i,j)/RGB(i,j);% rgb归一化gg(i,j)=G1(i,j)/RGB(i,j);x=[rr(i,j),gg(i,j)];p(i,j)=exp((-0・5)*(x-m)*inv(n)*(x-m)'); % 皮肤概率服从高斯分布endendendsubplot(2,3,2);imshow(p); % 显示皮肤灰度图像low_pass=1/9*ones(3);image_low=filter2(low_pass, p); % 低通滤波去噪声subplot(2,3,3);imshow(image」ow);%自适应阀值程序previousSkin2 = zeros(i,j);changelist =[];for threshold = 0・55:-0.1:0.05two_value = zeros(i,j);two_value(find(image_low>threshold)) = 1;change = sum(sum(two_value - previousSkin2));changelist = [changelist change];previousSkin2 = two_value;end[C, I] = min(changelist);optimalThreshold = (7-1)* 0.1two_value = zeros(i,j);two_value(find(image_low>optimalThreshold))= 1; %二值化subplot(2,3,4);imshow(two_value); % 显示二值图像我的照片人脸模板.jpg'); %读入人脸模板照片FaceCoord=[|;imsourcegray=rgb2gray(Ori_Face); % 将原照片转换为灰度图像[L,N]=bwlabel(two_value,8); % 标注二值图像中连接的部分丄为数据矩阵,N为颗粒的个数for i=1:N,[x,y]=find(bwlabel(two_value)==i); % 寻找矩阵中标号为i 的行和列的下标bwsegment = bwselect(two_value,y,x,8); % 选择出第i 个颗粒numholes = 1-bweuler(bwsegment,4); % 计算此区域的空洞数if (numholes >= 1) % 若此区域至少包含一个洞,则将其选出进行下一步运算RectCoord = -1;[m n] = size(bwsegment);[cx,cy]=center(bwsegment);%求此区域的质心bwnohole=bwfill(bwsegment,'holes'); % 将洞圭寸住(将灰度值赋为1)justface = uint8(double(bwnohole)・* double(imsourcegray));%只在原照片的灰度图像中保留该候选区域angle = orient(bwsegment,cx,cy); %求此区域的偏转角度bw = imrotate(bwsegment, angle, 'bilinear');bw = bwfill(bw,'holes');[l,r,u,d] =bianjie(bw);wx = (r - l +1); % 宽度ly = (d - u + 1); % 高度wratio = ly/wx % 高宽比if ((0 ・8v=wratio)&(wratiov=2))%如果目标区域的高度/宽度比例大于0・8且小于2.0,则将其选出进行下一步运算S=ly*wx; %计算包含此区域矩形的面积A=bwarea(bwsegment); %计算此区域面积if (A/S>0.35)[ccorr,mfit, RectCoord] =mobanpipei(justface,frontalmodel,ly,wx, cx,cy, angle);end if (ccorr>=0.6)mfitbw=(mfit>=1);invbw = xor(mfitbw,ones(size(mfitbw)));source_with_hole = uint8(double(invbw) double(imsourcegray));final_image = uint8(double(source_with_hole) double(mfit));subplot(2,3,5);imshow(final_image); % 显示覆盖了模板脸的灰度图像imsourcegray = final_image;subplot(2,3,6);imshow(Ori_Face); % 显示检测效果图end;if (RectCoord ~= -1)FaceCoord = [FaceCoord; RectCoord];endendendend%在认为是人脸的区域画矩形[numfaces x] = size(FaceCoord);for i=1:numfaces,hd = rectangle('Position',FaceCoord(i,:));set(hd, 'edgecolor', 'y');end人脸检测是人脸识别、人机交互、智能视觉监控等工作的前提。

人脸检测matlab代码

人脸检测matlab代码
[xt, yt] = meshgrid(round(linspace(1, size(I, 1), 10)), ...
round(linspace(1, size(I, 2), 10)));
mesh(yt, xt, zeros(size(xt)), 'FaceColor', ...
'None', 'LineWidth', 2, ...
subplot(1, 2, 2);mesh(p);title('实际肤色分布');
if ndims(Img) == 3
I=rgb2gray(Img);
else
I = Img;
end
J=imnoise(I,'salt & pepper',0.01);
I1=filter2(fspecial('average',3),J,'full')/255;
G1=im2double(G);
B1=im2double(B);
RGB=R1+G1+B1;
m=[ 0.4144,0.3174]; % 均值
n=[0.0031,-0.0004;-0.0004,0.0003]; % 方差
[x1,y1]=meshgrid(0:0.01:1,0:0.01:1);
'EdgeColor', 'b');
subplot(2, 4, 3); imshow(p);title('基于肤色概率分布的灰度图像');
subplot(2, 4, 4); imshow(I1);title('邻域平均法滤波后图像');

(完整版)人脸识别MATLAB代码

(完整版)人脸识别MATLAB代码

1.色彩空间转换function [r,g]=rgb_RGB(Ori_Face)R=Ori_Face(:,:,1);G=Ori_Face(:,:,2);B=Ori_Face(:,:,3);R1=im2double(R); % 将uint8型转换成double型G1=im2double(G);B1=im2double(B);RGB=R1+G1+B1;row=size(Ori_Face,1); % 行像素column=size(Ori_Face,2); % 列像素for i=1:rowfor j=1:columnrr(i,j)=R1(i,j)/RGB(i,j);gg(i,j)=G1(i,j)/RGB(i,j);endendrrr=mean(rr);r=mean(rrr);ggg=mean(gg);g=mean(ggg);2.均值和协方差t1=imread('D:\matlab\皮肤库\1.jpg');[r1,g1]=rgb_RGB(t1); t2=imread('D:\matlab\皮肤库\2.jpg');[r2,g2]=rgb_RGB(t2); t3=imread('D:\matlab\皮肤库\3.jpg');[r3,g3]=rgb_RGB(t3); t4=imread('D:\matlab\皮肤库\4.jpg');[r4,g4]=rgb_RGB(t4); t5=imread('D:\matlab\皮肤库\5.jpg');[r5,g5]=rgb_RGB(t5); t6=imread('D:\matlab\皮肤库\6.jpg');[r6,g6]=rgb_RGB(t6); t7=imread('D:\matlab\皮肤库\7.jpg');[r7,g7]=rgb_RGB(t7); t8=imread('D:\matlab\皮肤库\8.jpg');[r8,g8]=rgb_RGB(t8);t9=imread('D:\matlab\皮肤库\9.jpg');[r9,g9]=rgb_RGB(t9);t10=imread('D:\matlab\皮肤库\10.jpg');[r10,g10]=rgb_RGB(t10);t11=imread('D:\matlab\皮肤库\11.jpg');[r11,g11]=rgb_RGB(t11);t12=imread('D:\matlab\皮肤库\12.jpg');[r12,g12]=rgb_RGB(t12);t13=imread('D:\matlab\皮肤库\13.jpg');[r13,g13]=rgb_RGB(t13);t14=imread('D:\matlab\皮肤库\14.jpg');[r14,g14]=rgb_RGB(t14);t15=imread('D:\matlab\皮肤库\15.jpg');[r15,g15]=rgb_RGB(t15);t16=imread('D:\matlab\皮肤库\16.jpg');[r16,g16]=rgb_RGB(t16);t17=imread('D:\matlab\皮肤库\17.jpg');[r17,g17]=rgb_RGB(t17);t18=imread('D:\matlab\皮肤库\18.jpg');[r18,g18]=rgb_RGB(t18);t19=imread('D:\matlab\皮肤库\19.jpg');[r19,g19]=rgb_RGB(t19);t20=imread('D:\matlab\皮肤库\20.jpg');[r20,g20]=rgb_RGB(t20);t21=imread('D:\matlab\皮肤库\21.jpg');[r21,g21]=rgb_RGB(t21);t22=imread('D:\matlab\皮肤库\22.jpg');[r22,g22]=rgb_RGB(t22);t23=imread('D:\matlab\皮肤库\23.jpg');[r23,g23]=rgb_RGB(t23);t24=imread('D:\matlab\皮肤库\24.jpg');[r24,g24]=rgb_RGB(t24);t25=imread('D:\matlab\皮肤库\25.jpg');[r25,g25]=rgb_RGB(t25);t26=imread('D:\matlab\皮肤库\26.jpg');[r26,g26]=rgb_RGB(t26);t27=imread('D:\matlab\皮肤库\27.jpg');[r27,g27]=rgb_RGB(t27);r=cat(1,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16,r17,r18,r19,r20,r21,r22, r23,r24,r25,r26,r27);g=cat(1,g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11,g12,g13,g14,g15,g16,g17,g18,g19,g20 ,g21,g22,g23,g24,g25,g26,g27);m=mean([r,g])n=cov([r,g])3.求质心function [xmean, ymean] = center(bw)bw=bwfill(bw,'holes');area = bwarea(bw);[m n] =size(bw);bw=double(bw);xmean =0; ymean = 0;for i=1:m,for j=1:n,xmean = xmean + j*bw(i,j);ymean = ymean + i*bw(i,j);end;end;if(area==0)xmean=0;ymean=0;elsexmean = xmean/area;ymean = ymean/area;xmean = round(xmean);ymean = round(ymean);end4. 求偏转角度function [theta] = orient(bw,xmean,ymean) [m n] =size(bw);bw=double(bw);a = 0;b = 0;c = 0;for i=1:m,for j=1:n,a = a + (j - xmean)^2 * bw(i,j);b = b + (j - xmean) * (i - ymean) * bw(i,j);c = c + (i - ymean)^2 * bw(i,j);end;b = 2 * b;theta = atan(b/(a-c))/2;theta = theta*(180/pi); % 从幅度转换到角度5. 找区域边界function [left, right, up, down] = bianjie(A)[m n] = size(A);left = -1;right = -1;up = -1;down = -1;for j=1:n,for i=1:m,if (A(i,j) ~= 0)left = j;break;end;end;if (left ~= -1) break;end;end;for j=n:-1:1,for i=1:m,if (A(i,j) ~= 0)right = j;break;end;end;if (right ~= -1) break;end;for i=1:m,for j=1:n,if (A(i,j) ~= 0)up = i;break;end;end;if (up ~= -1)break;end;end;for i=m:-1:1,for j=1:n,if (A(i,j) ~= 0)down = i;break;end;end;if (down ~= -1)break;end;end;6. 求起始坐标function newcoord = checklimit(coord,maxval) newcoord = coord;if (newcoord<1)newcoord=1;end;if (newcoord>maxval)newcoord=maxval;end;7.模板匹配function [ccorr, mfit, RectCoord] = mobanpipei(mult, frontalmodel,ly,wx,cx, cy, angle)frontalmodel=rgb2gray(frontalmodel);model_rot = imresize(frontalmodel,[ly wx],'bilinear'); % 调整模板大小model_rot = imrotate(model_rot,angle,'bilinear'); % 旋转模板[l,r,u,d] = bianjie(model_rot); % 求边界坐标bwmodel_rot=imcrop(model_rot,[l u (r-l) (d-u)]); % 选择模板人脸区域[modx,mody] =center(bwmodel_rot); % 求质心[morig, norig] = size(bwmodel_rot);% 产生一个覆盖了人脸模板的灰度图像mfit = zeros(size(mult));mfitbw = zeros(size(mult));[limy, limx] = size(mfit);% 计算原图像中人脸模板的坐标startx = cx-modx;starty = cy-mody;endx = startx + norig-1;endy = starty + morig-1;startx = checklimit(startx,limx);starty = checklimit(starty,limy);endx = checklimit(endx,limx);endy = checklimit(endy,limy);for i=starty:endy,for j=startx:endx,mfit(i,j) = model_rot(i-starty+1,j-startx+1);end;end;ccorr = corr2(mfit,mult) % 计算相关度[l,r,u,d] = bianjie(bwmodel_rot);sx = startx+l;sy = starty+u;RectCoord = [sx sy (r-1) (d-u)]; % 产生矩形坐标8.主程序clear;[fname,pname]=uigetfile({'*.jpg';'*.bmp';'*.tif';'*.gif'},'Please choose a color picture...'); % 返回打开的图片名与图片路径名[u,v]=size(fname);y=fname(v); % 图片格式代表值switch ycase 0errordlg('You Should Load Image File First...','Warning...');case{'g';'G';'p';'P';'f';'F'}; % 图片格式若是JPG/jpg、BMP/bmp、TIF/tif 或者GIF/gif,才打开I=cat(2,pname,fname);Ori_Face=imread(I);subplot(2,3,1),imshow(Ori_Face);otherwiseerrordlg('You Should Load Image File First...','Warning...');endR=Ori_Face(:,:,1);G=Ori_Face(:,:,2);B=Ori_Face(:,:,3);R1=im2double(R); % 将uint8型转换成double型处理G1=im2double(G);B1=im2double(B);RGB=R1+G1+B1;m=[ 0.4144,0.3174]; % 均值n=[0.0031,-0.0004;-0.0004,0.0003]; % 方差row=size(Ori_Face,1); % 行像素数column=size(Ori_Face,2); % 列像素数for i=1:rowfor j=1:columnif RGB(i,j)==0rr(i,j)=0;gg(i,j)=0;elserr(i,j)=R1(i,j)/RGB(i,j); % rgb归一化gg(i,j)=G1(i,j)/RGB(i,j);x=[rr(i,j),gg(i,j)];p(i,j)=exp((-0.5)*(x-m)*inv(n)*(x-m)'); % 皮肤概率服从高斯分布endendendsubplot(2,3,2);imshow(p); % 显示皮肤灰度图像low_pass=1/9*ones(3);image_low=filter2(low_pass, p); % 低通滤波去噪声subplot(2,3,3);imshow(image_low);% 自适应阀值程序previousSkin2 = zeros(i,j);changelist = [];for threshold = 0.55:-0.1:0.05two_value = zeros(i,j);two_value(find(image_low>threshold)) = 1;change = sum(sum(two_value - previousSkin2));changelist = [changelist change];previousSkin2 = two_value;end[C, I] = min(changelist);optimalThreshold = (7-I)*0.1two_value = zeros(i,j);two_value(find(image_low>optimalThreshold)) = 1; % 二值化subplot(2,3,4);imshow(two_value); % 显示二值图像frontalmodel=imread('E:\我的照片\人脸模板.jpg'); % 读入人脸模板照片FaceCoord=[];imsourcegray=rgb2gray(Ori_Face); % 将原照片转换为灰度图像[L,N]=bwlabel(two_value,8); % 标注二值图像中连接的部分,L为数据矩阵,N为颗粒的个数for i=1:N,[x,y]=find(bwlabel(two_value)==i); % 寻找矩阵中标号为i的行和列的下标bwsegment = bwselect(two_value,y,x,8); % 选择出第i个颗粒numholes = 1-bweuler(bwsegment,4); % 计算此区域的空洞数if (numholes >= 1) % 若此区域至少包含一个洞,则将其选出进行下一步运算RectCoord = -1;[m n] = size(bwsegment);[cx,cy]=center(bwsegment); % 求此区域的质心bwnohole=bwfill(bwsegment,'holes'); % 将洞封住(将灰度值赋为1)justface = uint8(double(bwnohole) .* double(imsourcegray));% 只在原照片的灰度图像中保留该候选区域angle = orient(bwsegment,cx,cy); % 求此区域的偏转角度bw = imrotate(bwsegment, angle, 'bilinear');bw = bwfill(bw,'holes');[l,r,u,d] =bianjie(bw);wx = (r - l +1); % 宽度ly = (d - u + 1); % 高度wratio = ly/wx % 高宽比if ((0.8<=wratio)&(wratio<=2))% 如果目标区域的高度/宽度比例大于0.8且小于2.0,则将其选出进行下一步运算S=ly*wx; % 计算包含此区域矩形的面积A=bwarea(bwsegment); % 计算此区域面积if (A/S>0.35)[ccorr,mfit, RectCoord] = mobanpipei(justface,frontalmodel,ly,wx, cx,cy, angle);endif (ccorr>=0.6)mfitbw=(mfit>=1);invbw = xor(mfitbw,ones(size(mfitbw)));source_with_hole = uint8(double(invbw) .* double(imsourcegray));final_image = uint8(double(source_with_hole) + double(mfit));subplot(2,3,5);imshow(final_image); % 显示覆盖了模板脸的灰度图像imsourcegray = final_image;subplot(2,3,6);imshow(Ori_Face); % 显示检测效果图end;if (RectCoord ~= -1)FaceCoord = [FaceCoord; RectCoord];endendendend% 在认为是人脸的区域画矩形[numfaces x] = size(FaceCoord);for i=1:numfaces,hd = rectangle('Position',FaceCoord(i,:));set(hd, 'edgecolor', 'y');end人脸检测是人脸识别、人机交互、智能视觉监控等工作的前提。

肤色分割人脸检测matlab代码

肤色分割人脸检测matlab代码

image = imread('im.jpg');figure,imshow(image);red = double(image(:,:,1));green = double(image(:,:,2));blue = double(image(:,:,3));[m n]=size(red);Y = zeros(m,n);Cb = zeros(m,n);Cr = zeros(m,n);I = zeros(m,n);Q = zeros(m,n);red_gama = zeros(m,n);green_gama = zeros(m,n);blue_gama = zeros(m,n);for i=1:m %gamma矫正for j=1:nif red(i,j)>0 && red(i,j)<90fai=pi*red(i,j)/180;gama=1+0.5*cos(fai);red_gama(i,j)=255*(red(i,j)/255)^(1/gama);elseif red(i,j)>=90 && red(i,j)<=170fai=pi/2;gama=1+0.5*cos(fai);red_gama(i,j)=255*(red(i,j)/255)^(1/gama);elseif red(i,j)>170 && red(i,j)<=255fai=pi-pi*(255-red(i,j))/170;gama=1+0.5*cos(fai);red_gama(i,j)=255*(red(i,j)/255)^(1/gama);endif green(i,j)>0 && green(i,j)<90fai=pi*green(i,j)/180;gama=1+0.5*cos(fai);green_gama(i,j)=255*(green(i,j)/255)^(1/gama);elseif green(i,j)>=90 && green(i,j)<=170fai=pi/2;gama=1+0.5*cos(fai);green_gama(i,j)=255*(green(i,j)/255)^(1/gama);elseif green(i,j)>170 && green(i,j)<=255fai=pi-pi*(255-green(i,j))/170;gama=1+0.5*cos(fai);green_gama(i,j)=255*(green(i,j)/255)^(1/gama);endif blue(i,j)>0 && blue(i,j)<90fai=pi*blue(i,j)/180;gama=1+0.5*cos(fai);blue_gama(i,j)=255*(blue(i,j)/255)^(1/gama);elseif blue(i,j)>=90 && blue(i,j)<=170fai=pi/2;gama=1+0.5*cos(fai);blue_gama(i,j)=255*(blue(i,j)/255)^(1/gama);elseif blue(i,j)>170 && blue(i,j)<=255fai=pi-pi*(255-blue(i,j))/170;gama=1+0.5*cos(fai);blue_gama(i,j)=255*(blue(i,j)/255)^(1/gama);endendendfor i=1:mfor j=1:nY(i,j)=0.2989*red_gama(i,j)+0.5866*green_gama(i,j)+0.1145*blue_gama(i,j) ;Cb(i,j)=-0.1688*red_gama(i,j)-0.3312*green_gama(i,j)+0.5000*blue_gama(iCr(i,j)=0.5000*red_gama(i,j)-0.4184*green_gama(i,j)-0.0817*blue_gama(i,j) ;endendemp=zeros(m,n);sita=zeros(m,n);for i=1:mfor j=1:nif Cr(i,j)>0 && Cb(i,j)>0sita(i,j)=atan(abs(Cr(i,j))/abs(Cb(i,j)))*180/pi;elseif Cr(i,j)>0 && Cb(i,j)<0sita(i,j)=180-atan(abs(Cr(i,j))/abs(Cb(i,j)))*180/pi;elseif Cr(i,j)<0 && Cb(i,j)<0sita(i,j)=180 + atan(abs(Cr(i,j))/abs(Cb(i,j)))*180/pi;elsesita(i,j)=0;endendendfor i=1:mfor j=1:nif sita(i,j)>105 && sita(i,j)<150emp(i,j)=sita(i,j);elseemp(i,j)=0;Y(i,j)=0;endendfigure,imshow(emp); figure,imshow(uint8(Y));原图像分割结果分割结果。

基于肤色信息的人脸检测MATLAB程序

基于肤色信息的人脸检测MATLAB程序

clear allclose allclc%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 读入待检测图像x=imread('C:\Documents and Settings\Administrator.30178A3145BA4BF\桌面\2.jpg'); %读入图像figureimshow(x)if size(x,3)>1x=rgb2gray(x);%转化为灰度图endx=double(x); %转化为小数型[output,count,m,svec]=facefind(x);%找出人脸,output返回人脸位置和大小信息,count为人脸个数信息,m实际检测到的最大人脸和最小人脸信息imagesc(x)colormap(gray) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 画出人脸框图col=[1 0 0];%人脸框图为红色col=[0 1 0];%人脸框图为绿色t=2; %人脸框图线的宽度N=size(output,2);if (N>0)for i=1:Nx1=output(1,i);x2=output(2,i);y1=output(3,i);y2=output(4,i);vec=[x1 x2 y1 y2]; %方框四个角的坐标ind=find(isinf(vec)); %无限值情况a=200; %should be realmaxvec(ind)=sign(vec(ind))*a;h1=line([vec(1) vec(2)],[vec(3) vec(3)]);h2=line([vec(2) vec(2)],[vec(3) vec(4)]);h3=line([vec(1) vec(2)],[vec(4) vec(4)]);h4=line([vec(1) vec(1)],[vec(3) vec(4)]);h=[h1 h2 h3 h4];set(h,'Color',col);set(h,'LineWidth',t)endend%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% minf=m(1);maxf=m(2);ex1=size(x,1)*0.01;ex1e=size(x,1)*0.02;ex2=size(x,1)*0.04;ex2e=size(x,1)*0.05;bx1=[0 maxf maxf 0];by1=[ex1e ex1e ex1 ex1];bx2=[0 minf minf 0];by2=[ex2e ex2e ex2 ex2];hold onfill(bx1,by1,[0 1 0])fill(bx2,by2,[0 1 0])hold off。

(完整版)人脸识别MATLAB代码

(完整版)人脸识别MATLAB代码

1.色彩空间转换function [r,g]=rgb_RGB(Ori_Face)R=Ori_Face(:,:,1);G=Ori_Face(:,:,2);B=Ori_Face(:,:,3);R1=im2double(R); % 将uint8型转换成double型G1=im2double(G);B1=im2double(B);RGB=R1+G1+B1;row=size(Ori_Face,1); % 行像素column=size(Ori_Face,2); % 列像素for i=1:rowfor j=1:columnrr(i,j)=R1(i,j)/RGB(i,j);gg(i,j)=G1(i,j)/RGB(i,j);endendrrr=mean(rr);r=mean(rrr);ggg=mean(gg);g=mean(ggg);2.均值和协方差t1=imread('D:\matlab\皮肤库\1.jpg');[r1,g1]=rgb_RGB(t1); t2=imread('D:\matlab\皮肤库\2.jpg');[r2,g2]=rgb_RGB(t2); t3=imread('D:\matlab\皮肤库\3.jpg');[r3,g3]=rgb_RGB(t3); t4=imread('D:\matlab\皮肤库\4.jpg');[r4,g4]=rgb_RGB(t4); t5=imread('D:\matlab\皮肤库\5.jpg');[r5,g5]=rgb_RGB(t5); t6=imread('D:\matlab\皮肤库\6.jpg');[r6,g6]=rgb_RGB(t6); t7=imread('D:\matlab\皮肤库\7.jpg');[r7,g7]=rgb_RGB(t7); t8=imread('D:\matlab\皮肤库\8.jpg');[r8,g8]=rgb_RGB(t8);t9=imread('D:\matlab\皮肤库\9.jpg');[r9,g9]=rgb_RGB(t9);t10=imread('D:\matlab\皮肤库\10.jpg');[r10,g10]=rgb_RGB(t10);t11=imread('D:\matlab\皮肤库\11.jpg');[r11,g11]=rgb_RGB(t11);t12=imread('D:\matlab\皮肤库\12.jpg');[r12,g12]=rgb_RGB(t12);t13=imread('D:\matlab\皮肤库\13.jpg');[r13,g13]=rgb_RGB(t13);t14=imread('D:\matlab\皮肤库\14.jpg');[r14,g14]=rgb_RGB(t14);t15=imread('D:\matlab\皮肤库\15.jpg');[r15,g15]=rgb_RGB(t15);t16=imread('D:\matlab\皮肤库\16.jpg');[r16,g16]=rgb_RGB(t16);t17=imread('D:\matlab\皮肤库\17.jpg');[r17,g17]=rgb_RGB(t17);t18=imread('D:\matlab\皮肤库\18.jpg');[r18,g18]=rgb_RGB(t18);t19=imread('D:\matlab\皮肤库\19.jpg');[r19,g19]=rgb_RGB(t19);t20=imread('D:\matlab\皮肤库\20.jpg');[r20,g20]=rgb_RGB(t20);t21=imread('D:\matlab\皮肤库\21.jpg');[r21,g21]=rgb_RGB(t21);t22=imread('D:\matlab\皮肤库\22.jpg');[r22,g22]=rgb_RGB(t22);t23=imread('D:\matlab\皮肤库\23.jpg');[r23,g23]=rgb_RGB(t23);t24=imread('D:\matlab\皮肤库\24.jpg');[r24,g24]=rgb_RGB(t24);t25=imread('D:\matlab\皮肤库\25.jpg');[r25,g25]=rgb_RGB(t25);t26=imread('D:\matlab\皮肤库\26.jpg');[r26,g26]=rgb_RGB(t26);t27=imread('D:\matlab\皮肤库\27.jpg');[r27,g27]=rgb_RGB(t27);r=cat(1,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16,r17,r18,r19,r20,r21,r22, r23,r24,r25,r26,r27);g=cat(1,g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11,g12,g13,g14,g15,g16,g17,g18,g19,g20 ,g21,g22,g23,g24,g25,g26,g27);m=mean([r,g])n=cov([r,g])3.求质心function [xmean, ymean] = center(bw)bw=bwfill(bw,'holes');area = bwarea(bw);[m n] =size(bw);bw=double(bw);xmean =0; ymean = 0;for i=1:m,for j=1:n,xmean = xmean + j*bw(i,j);ymean = ymean + i*bw(i,j);end;end;if(area==0)xmean=0;ymean=0;elsexmean = xmean/area;ymean = ymean/area;xmean = round(xmean);ymean = round(ymean);end4. 求偏转角度function [theta] = orient(bw,xmean,ymean) [m n] =size(bw);bw=double(bw);a = 0;b = 0;c = 0;for i=1:m,for j=1:n,a = a + (j - xmean)^2 * bw(i,j);b = b + (j - xmean) * (i - ymean) * bw(i,j);c = c + (i - ymean)^2 * bw(i,j);end;b = 2 * b;theta = atan(b/(a-c))/2;theta = theta*(180/pi); % 从幅度转换到角度5. 找区域边界function [left, right, up, down] = bianjie(A)[m n] = size(A);left = -1;right = -1;up = -1;down = -1;for j=1:n,for i=1:m,if (A(i,j) ~= 0)left = j;break;end;end;if (left ~= -1) break;end;end;for j=n:-1:1,for i=1:m,if (A(i,j) ~= 0)right = j;break;end;end;if (right ~= -1) break;end;for i=1:m,for j=1:n,if (A(i,j) ~= 0)up = i;break;end;end;if (up ~= -1)break;end;end;for i=m:-1:1,for j=1:n,if (A(i,j) ~= 0)down = i;break;end;end;if (down ~= -1)break;end;end;6. 求起始坐标function newcoord = checklimit(coord,maxval) newcoord = coord;if (newcoord<1)newcoord=1;end;if (newcoord>maxval)newcoord=maxval;end;7.模板匹配function [ccorr, mfit, RectCoord] = mobanpipei(mult, frontalmodel,ly,wx,cx, cy, angle)frontalmodel=rgb2gray(frontalmodel);model_rot = imresize(frontalmodel,[ly wx],'bilinear'); % 调整模板大小model_rot = imrotate(model_rot,angle,'bilinear'); % 旋转模板[l,r,u,d] = bianjie(model_rot); % 求边界坐标bwmodel_rot=imcrop(model_rot,[l u (r-l) (d-u)]); % 选择模板人脸区域[modx,mody] =center(bwmodel_rot); % 求质心[morig, norig] = size(bwmodel_rot);% 产生一个覆盖了人脸模板的灰度图像mfit = zeros(size(mult));mfitbw = zeros(size(mult));[limy, limx] = size(mfit);% 计算原图像中人脸模板的坐标startx = cx-modx;starty = cy-mody;endx = startx + norig-1;endy = starty + morig-1;startx = checklimit(startx,limx);starty = checklimit(starty,limy);endx = checklimit(endx,limx);endy = checklimit(endy,limy);for i=starty:endy,for j=startx:endx,mfit(i,j) = model_rot(i-starty+1,j-startx+1);end;end;ccorr = corr2(mfit,mult) % 计算相关度[l,r,u,d] = bianjie(bwmodel_rot);sx = startx+l;sy = starty+u;RectCoord = [sx sy (r-1) (d-u)]; % 产生矩形坐标8.主程序clear;[fname,pname]=uigetfile({'*.jpg';'*.bmp';'*.tif';'*.gif'},'Please choose a color picture...'); % 返回打开的图片名与图片路径名[u,v]=size(fname);y=fname(v); % 图片格式代表值switch ycase 0errordlg('You Should Load Image File First...','Warning...');case{'g';'G';'p';'P';'f';'F'}; % 图片格式若是JPG/jpg、BMP/bmp、TIF/tif 或者GIF/gif,才打开I=cat(2,pname,fname);Ori_Face=imread(I);subplot(2,3,1),imshow(Ori_Face);otherwiseerrordlg('You Should Load Image File First...','Warning...');endR=Ori_Face(:,:,1);G=Ori_Face(:,:,2);B=Ori_Face(:,:,3);R1=im2double(R); % 将uint8型转换成double型处理G1=im2double(G);B1=im2double(B);RGB=R1+G1+B1;m=[ 0.4144,0.3174]; % 均值n=[0.0031,-0.0004;-0.0004,0.0003]; % 方差row=size(Ori_Face,1); % 行像素数column=size(Ori_Face,2); % 列像素数for i=1:rowfor j=1:columnif RGB(i,j)==0rr(i,j)=0;gg(i,j)=0;elserr(i,j)=R1(i,j)/RGB(i,j); % rgb归一化gg(i,j)=G1(i,j)/RGB(i,j);x=[rr(i,j),gg(i,j)];p(i,j)=exp((-0.5)*(x-m)*inv(n)*(x-m)'); % 皮肤概率服从高斯分布endendendsubplot(2,3,2);imshow(p); % 显示皮肤灰度图像low_pass=1/9*ones(3);image_low=filter2(low_pass, p); % 低通滤波去噪声subplot(2,3,3);imshow(image_low);% 自适应阀值程序previousSkin2 = zeros(i,j);changelist = [];for threshold = 0.55:-0.1:0.05two_value = zeros(i,j);two_value(find(image_low>threshold)) = 1;change = sum(sum(two_value - previousSkin2));changelist = [changelist change];previousSkin2 = two_value;end[C, I] = min(changelist);optimalThreshold = (7-I)*0.1two_value = zeros(i,j);two_value(find(image_low>optimalThreshold)) = 1; % 二值化subplot(2,3,4);imshow(two_value); % 显示二值图像frontalmodel=imread('E:\我的照片\人脸模板.jpg'); % 读入人脸模板照片FaceCoord=[];imsourcegray=rgb2gray(Ori_Face); % 将原照片转换为灰度图像[L,N]=bwlabel(two_value,8); % 标注二值图像中连接的部分,L为数据矩阵,N为颗粒的个数for i=1:N,[x,y]=find(bwlabel(two_value)==i); % 寻找矩阵中标号为i的行和列的下标bwsegment = bwselect(two_value,y,x,8); % 选择出第i个颗粒numholes = 1-bweuler(bwsegment,4); % 计算此区域的空洞数if (numholes >= 1) % 若此区域至少包含一个洞,则将其选出进行下一步运算RectCoord = -1;[m n] = size(bwsegment);[cx,cy]=center(bwsegment); % 求此区域的质心bwnohole=bwfill(bwsegment,'holes'); % 将洞封住(将灰度值赋为1)justface = uint8(double(bwnohole) .* double(imsourcegray));% 只在原照片的灰度图像中保留该候选区域angle = orient(bwsegment,cx,cy); % 求此区域的偏转角度bw = imrotate(bwsegment, angle, 'bilinear');bw = bwfill(bw,'holes');[l,r,u,d] =bianjie(bw);wx = (r - l +1); % 宽度ly = (d - u + 1); % 高度wratio = ly/wx % 高宽比if ((0.8<=wratio)&(wratio<=2))% 如果目标区域的高度/宽度比例大于0.8且小于2.0,则将其选出进行下一步运算S=ly*wx; % 计算包含此区域矩形的面积A=bwarea(bwsegment); % 计算此区域面积if (A/S>0.35)[ccorr,mfit, RectCoord] = mobanpipei(justface,frontalmodel,ly,wx, cx,cy, angle);endif (ccorr>=0.6)mfitbw=(mfit>=1);invbw = xor(mfitbw,ones(size(mfitbw)));source_with_hole = uint8(double(invbw) .* double(imsourcegray));final_image = uint8(double(source_with_hole) + double(mfit));subplot(2,3,5);imshow(final_image); % 显示覆盖了模板脸的灰度图像imsourcegray = final_image;subplot(2,3,6);imshow(Ori_Face); % 显示检测效果图end;if (RectCoord ~= -1)FaceCoord = [FaceCoord; RectCoord];endendendend% 在认为是人脸的区域画矩形[numfaces x] = size(FaceCoord);for i=1:numfaces,hd = rectangle('Position',FaceCoord(i,:));set(hd, 'edgecolor', 'y');end人脸检测是人脸识别、人机交互、智能视觉监控等工作的前提。

完整版)基于matlab程序实现人脸识别

完整版)基于matlab程序实现人脸识别

完整版)基于matlab程序实现人脸识别Based on MATLAB program。

face n is implemented。

1.Face n Process1.1.1 Basic PrincipleXXX carried out based on the YCbCr color space skin color model。

It has been found that the skin color clustering n in the Cb-Cr subplane n of the YCbCr color space will be XXX different from the central n。

Using this method。

image XXX-faces。

1.1.2 FlowchartXXX:1.Read the original image2.Convert the image to the YCbCr color spacee the skin color model to binarize the image and perform morphological processing4.Select the white area in the binary image。

measure the area attributes。

and filter to obtain all rectangular blocks5.Filter specific areas (height-to-width。

een 0.6 and 2.eye features)6.Store the rectangular area of the face7.Filter special areas based on other n and mark the final face area2.Face n Program1) Face and Non-XXXn result = skin(Y,Cb,Cr)SKIN Summary of this n goes hereDetailed n goes herea=25.39;b=14.03;ecx=1.60;ecy=2.41;sita=2.53;cx=109.38;cy=152.02;xishu=[cos(sita) sin(sita);-sin(sita) cos(sita)];If the brightness is greater than 230.the major and minor axes are expanded by 1.1 timesif(Y>230)a=1.1*a;b=1.1*b;endXXXCb=double(Cb);Cr=double(Cr);t=[(Cb-cx);(Cr-cy)];temp=xishu*t;value=(temp(1)-ecx)^2/a^2+(temp(2)-ecy)^2/b^2;If the value is greater than 1.it is not skin color and returns。

MATLAB人脸识别源代码

MATLAB人脸识别源代码

MATLAB人脸识别源代码% FaceRec.m %CQUPT% PCA 识别率88%% calc xmean,sigma and its eigen decompositionallsamples=[];%所有训练图片for i=1:40for j=1:5a=imread(strcat('e:\ORL\s',num2str(i),'\',num2str(j),'.pgm'));b=a(1:112*92); %b是行矢量1*N,N=10304,提取顺序是先列后行,%即从上到下,从左到右b=double(b);allsamples=[allsamples;b]; %allsamples是一个M*N矩阵,allsamples中每一行数据代%表一张图片,其中M=200endendsamplemean=mean(allsamples); %平均图片,1*N for i=1:200xmean(i,:)=allsamples(i,:)-samplemean; %allsamples是一个M*N矩阵,allsamples中每一行保存的数据是“每个图片数据—平均图片”end;%获取特征植及特征向量sigma=xmean*xmean'; % M* M矩阵[v d]=eig(sigma);d1=diag(d);%按特征值大小以降序排列dsort=flipud(d1);vsort=fliplr(v);%以下选择90%的能量dsum=sum(dsort);dsum_extract=0;p=0;while(dsum_extract/dsum<0.9) p=p+1;dsum_extract=sum(dsort(1:p)); endi=1;% (训练阶段)计算特征脸形成的坐标系base = xmean' * vsort(:,1:p) * diag(dsort(1:p).^(-1/2));%base是N*p阶矩阵,除以dsort(i) ^(-1/2))是对人脸图象的标准化(是其方差为1)% xmean' * vsort(:,1:p)是小矩阵的特征向量向大矩阵特征向量转换的过程%以下两行将训练样本对坐标系上进行投影,得到一个M*p子空间中的一个点,%即在子空间中的组合系数allcoor=allsamples*base;accu = 0; %下面的人脸识别过程中就是利用这些组合系数来进行识别%测试过程for i=1:40for j=6:10 %读入40 x 5 副测试图像a=imread(strcat('e:\ORL\s',num2str(i),'\',num2str(j),'.pgm'));b=a(1:10304);b=double(b);tcoor=b*base; %计算坐标,是1*p阶矩阵for k=1:200mdist(k)=norm(tcoor-allcoor(k,:)); end;%三阶近邻[dist,index2]=sort(mdist); class1=floor( (index2(1)-1)/5 )+1;class2=floor((index2(2)-1)/5)+1;class3=floor((index2(3)-1)/5)+1; if class1~=class2 && class2~=class3 class=class1;elseif class1==class2class=class1;elseif class2==class3class=class2;end;if class==iaccu=accu+1;end;end;end;accuracy=accu/200 % 输出识别率% FaceRec.m %CQUPT% PCA 识别率88%% calc xmean,sigma and its eigen decompositionallsamples=[]; %所有训练图片for i=1:40for j=1:5a=imread(strcat('e:\ORL\s',num2str(i),'\',num2str(j),'.pgm'));b=a(1:112*92); %b是行矢量1*N,N=10304,提取顺序是先列后行,%即从上到下,从左到右b=double(b);allsamples=[allsamples;b]; %allsamples是一个M*N矩阵,allsamples中每一行数据代%表一张图片,其中M=200endendsamplemean=mean(allsamples); %平均图片,1*Nfor i=1:200 xmean(i,:)=allsamples(i,:)-samplemean; %allsamples是一个M*N矩阵,allsamples中每一行保存 %的数据是“每个图片数据—平均图片” end;%获取特征植及特征向量sigma=xmean*xmean'; % M* M矩阵 [v d]=eig(sigma); d1=diag(d);%按特征值大小以降序排列dsort=flipud(d1); vsort=fliplr(v); %以下选择90%的能量dsum=sum(dsort);dsum_extract=0;p=0;while(dsum_extract/dsum<0.9) p=p+1;dsum_extract=sum(dsort(1:p)); endp=199;% (训练阶段)计算特征脸形成的坐标系base = xmean' * vsort(:,1:p) * diag(dsort(1:p).^(-1/2));%生成特征脸for(k=1:p)temp=reshape(base(:,k),112,92); newpath=[…e:\test\? int2str(k)….jpg?];imwrite(mat2gray(temp), newpath); end%将模型保存Save(…e:\ORL\model.mat? ,?base?, …samplemean?);%Reconstruct.m % CQUPTFunction[]=reconstruct() Load e:\ORL\model.mat;%计算新图片在特征子空间中的系数Img=?D:\test2\10.jpg?A=imread(img);b=a(1:112*92); % b是行矢量 1*N,其中N =10304 b=double(b);b=b-samplemean;c = b * base; % c 是图片 a在子空间中的系数, 是 1*p 行矢量 % 根据特征系数及特征脸重建图% 前15 个t = 15;temp = base(:,1:t) * c(1:t)'; temp = temp + samplemean';imwrite(mat2gray(reshape(temp, 112,92)),'d:\test2\t1.jpg');% 前50个t = 50;temp = base(:,1:t) * c(1:t)'; temp = temp + samplemean';imwrite(mat2gray(reshape(temp, 112,92)),'d:\test2\t2.jpg');% 前 100个t = 100;temp = base(:,1:t) * c(1:t)'; temp = temp + samplemean';imwrite(mat2gray(reshape(temp, 112,92)),'d:\test2\t3.jpg');% 前150个t = 150;temp = base(:,1:t) * c(1:t)'; temp = temp + samplemean';imwrite(mat2gray(reshape(temp, 112,92)),'d:\test2\t4.jpg');% 前199 个t = 199;temp = base(:,1:t) * c(1:t)'; temp = temp + samplemean';imwrite(mat2gray(reshape(temp, 112,92)),'d:\test2\t5.jpg');图片标准化通常是一个整体概念,要求把图片归一到均值为0,方差为1的情况下。

基于某matlab程序实现人脸识别

基于某matlab程序实现人脸识别

基于matlab程序实现人脸识别1.人脸识别流程1.1.1基本原理基于YCbCr颜色空间的肤色模型进行肤色分割。

在YCbCr色彩空间内对肤色进行了建模发现,肤色聚类区域在Cb—Cr子平面上的投影将缩减,与中心区域显著不同。

采用这种方法的图像分割已经能够较为精确的将人脸和非人脸分割开来。

1.1.2流程图人脸识别流程图读入原始图像将图像转化为YCbCr颜色空间利用肤色模型二值化图像并作形态学处理选取出二值图像中的白色区域,度量区域属性,筛选后得到所有矩形块否筛选特定区域(高度和宽度的比率在(0.6~2)之间,眼睛特征)是存储人脸的矩形区域特殊区域根据其他信息筛选,标记最终的人脸区域2.人脸识别程序(1)人脸和非人脸区域分割程序function result = skin(Y,Cb,Cr)%SKIN Summary of this function goes here% Detailed explanation goes herea=25.39;b=14.03;ecx=1.60;ecy=2.41;sita=2.53;cx=109.38;cy=152.02;xishu=[cos(sita) sin(sita);-sin(sita) cos(sita)]; %如果亮度大于230,则将长短轴同时扩大为原来的1.1倍if(Y>230)a=1.1*a;b=1.1*b;end%根据公式进行计算Cb=double(Cb);Cr=double(Cr);t=[(Cb-cx);(Cr-cy)];temp=xishu*t;value=(temp(1)-ecx)^2/a^2+(temp(2)-ecy)^2/b^2;%大于1则不是肤色,返回0;否则为肤色,返回1if value>1result=0;elseresult=1;endend(2)人脸的确认程序function eye = findeye(bImage,x,y,w,h)%FINDEYE Summary of this function goes here % Detailed explanation goes herepart=zeros(h,w);%二值化for i=y:(y+h)for j=x:(x+w)if bImage(i,j)==0part(i-y+1,j-x+1)=255;elsepart(i-y+1,j-x+1)=0;endendend[L,num]=bwlabel(part,8);%如果区域中有两个以上的矩形则认为有眼睛if num<2eye=0;elseeye=1;endend(3)人脸识别主程序clear all;%读入原始图像I=imread('face3.jpg');gray=rgb2gray(I);ycbcr=rgb2ycbcr(I);%将图像转化为YCbCr空间heighth=size(gray,1);%读取图像尺寸width=size(gray,2);for i=1:heighth %利用肤色模型二值化图像for j=1:widthY=ycbcr(i,j,1);Cb=ycbcr(i,j,2);Cr=ycbcr(i,j,3);if(Y<80)gray(i,j)=0;elseif(skin(Y,Cb,Cr)==1)%根据色彩模型进行图像二值化 gray(i,j)=255;elsegray(i,j)=0;endendendendse=strel('arbitrary',eye(5));%二值图像形态学处理gray=imopen(gray,se);figure;imshow(gray)[L,num]=bwlabel(gray,8);%采用标记方法选出图中的白色区域stats=regionprops(L,'BoundingBox');%度量区域属性n=1;%存放经过筛选以后得到的所有矩形块result=zeros(n,4);figure,imshow(I);hold on;for i=1:num %开始筛选特定区域box=stats(i).BoundingBox;x=box(1);%矩形坐标Xy=box(2);%矩形坐标Yw=box(3);%矩形宽度wh=box(4);%矩形高度hratio=h/w;%宽度和高度的比例ux=uint16(x);uy=uint8(y);if ux>1ux=ux-1;endif uy>1uy=uy-1;endif w<20 || h<20|| w*h<400 %矩形长宽的范围和矩形的面积可自行设定continueelseif ratio<2 && ratio>0.6 && findeye(gray,ux,uy,w,h)==1 %根据“三庭五眼”规则高度和宽度比例应该在(0.6,2)内;result(n,:)=[ux uy w h];n=n+1;endendif size(result,1)==1 && result(1,1)>0 %对可能是人脸的区域进行标记rectangle('Position',[result(1,1),result(1,2),result(1,3),result(1,4) ],'EdgeColor','r');else%如果满足条件的矩形区域大于1,则再根据其他信息进行筛选arr1=[];arr2=[];for m=1:size(result,1)m1=result(m,1);m2=result(m,2);m3=result(m,3);m4=result(m,4);%得到符合和人脸匹配的数据if m1+m3<width && m2+m4<heighth && m3<0.2*widtha=a+1;arr1(a)=m3;arr2(a)=m4;%rectangle('Position',[m1,m2,m3,m4],'EdgeColor','r');endend%得到人脸长度和宽度的最小区域arr3=[];arr3=sort(arr1,'ascend');arr4=[];arr4=sort(arr2,'ascend');%根据得到的数据标定最终的人脸区域for m=1:size(result,1)m1=result(m,1);m2=result(m,2);m3=result(m,3);m4=result(m,4);%最终标定人脸if m1+m3<width && m2+m4<heighth && m3<0.2*widthm3=arr3(1);m4=arr4(1);rectangle('Position',[m1,m2,m3,m4],'EdgeColor','r');endend(4)程序说明人脸识别程序主要包含三个程序模块,人脸识别主程序由三部分构成。

照片人脸检测MATLAB代码

照片人脸检测MATLAB代码

% 载入图像Img = imread('star1.jpg');if ndims(Img) == 3I=rgb2gray(Img);elseI = Img;endBW = im2bw(I, graythresh(I)); % 二值化figure;subplot(2, 2, 1); imshow(Img);title('原图像', 'FontWeight', 'Bold');subplot(2, 2, 2); imshow(Img);title('网格标记图像', 'FontWeight', 'Bold');hold on;[xt, yt] = meshgrid(round(linspace(1, size(I, 1), 10)), ...round(linspace(1, size(I, 2), 10)));mesh(yt, xt, zeros(size(xt)), 'FaceColor', ...'None', 'LineWidth', 3, ...'EdgeColor', 'r');subplot(2, 2, 3); imshow(BW);title('二值图像', 'FontWeight', 'Bold');[n1, n2] = size(BW);r = floor(n1/10); % 分成10块,行c = floor(n2/10); % 分成10块,列x1 = 1; x2 = r; % 对应行初始化s = r*c; % 块面积for i = 1:10y1 = 1; y2 = c; % 对应列初始化for j = 1:10if (y2<=c || y2>=9*c) || (x1==1 || x2==r*10)% 如果是在四周区域loc = find(BW(x1:x2, y1:y2)==0);[p, q] = size(loc);pr = p/s*100; % 黑色像素所占的比例数if pr <= 100BW(x1:x2, y1:y2) = 0;endendy1 = y1+c; % 列跳跃y2 = y2+c; % 列跳跃endx1 = x1+r; % 行跳跃x2 = x2+r; % 行跳跃end[L, num] = bwlabel(BW, 8); % 区域标记stats = regionprops(L, 'BoundingBox'); % 得到包围矩形框Bd = cat(1, stats.BoundingBox);[s1, s2] = size(Bd);mx = 0;for k = 1:s1p = Bd(k, 3)*Bd(k, 4); % 宽*高if p>mx && (Bd(k, 3)/Bd(k, 4))<1.8% 如果满足面积块大,而且宽/高<1.8mx = p;j = k;endendsubplot(2, 2, 4);imshow(I); hold on;rectangle('Position', Bd(j, :), ...'EdgeColor', 'r', 'LineWidth', 3);title('标记图像', 'FontWeight', 'Bold');if ndims(Img) == 3I=rgb2gray(Img);elseI = Img;endBW = im2bw(I, graythresh(I)); % 二值化figure;subplot(2, 2, 1); imshow(Img);title('原图像', 'FontWeight', 'Bold');subplot(2, 2, 2); imshow(Img);title('网格标记图像', 'FontWeight', 'Bold');hold on;[xt, yt] = meshgrid(round(linspace(1, size(I, 1), 10)), ...round(linspace(1, size(I, 2), 10)));mesh(yt, xt, zeros(size(xt)), 'FaceColor', ...'None', 'LineWidth', 3, ...'EdgeColor', 'r');subplot(2, 2, 3); imshow(BW);title('二值图像', 'FontWeight', 'Bold');[n1, n2] = size(BW);r = floor(n1/10); % 分成10块,行c = floor(n2/10); % 分成10块,列x1 = 1; x2 = r; % 对应行初始化s = r*c; % 块面积for i = 1:10y1 = 1; y2 = c; % 对应列初始化for j = 1:10if (y2<=c || y2>=9*c) || (x1==1 || x2==r*10)% 如果是在四周区域loc = find(BW(x1:x2, y1:y2)==0);[p, q] = size(loc);pr = p/s*100; % 黑色像素所占的比例数if pr <= 100BW(x1:x2, y1:y2) = 0;endendy1 = y1+c; % 列跳跃y2 = y2+c; % 列跳跃endx1 = x1+r; % 行跳跃x2 = x2+r; % 行跳跃end[L, num] = bwlabel(BW, 8); % 区域标记stats = regionprops(L, 'BoundingBox'); % 得到包围矩形框Bd = cat(1, stats.BoundingBox);[s1, s2] = size(Bd);mx = 0;for k = 1:s1p = Bd(k, 3)*Bd(k, 4); % 宽*高if p>mx && (Bd(k, 3)/Bd(k, 4))<1.8% 如果满足面积块大,而且宽/高<1.8mx = p;j = k;endendsubplot(2, 2, 4);imshow(I); hold on;rectangle('Position', Bd(j, :), ...'EdgeColor', 'r', 'LineWidth', 3);title('标记图像', 'FontWeight', 'Bold');。

基于matlab程序实现人脸识别

基于matlab程序实现人脸识别

For personal use only in study andresearch; not for commercial use基于matlab程序实现人脸识别1.人脸识别流程基于YCbCr颜色空间的肤色模型进行肤色分割。

在YCbCr色彩空间内对肤色进行了建模发现,肤色聚类区域在Cb—Cr子平面上的投影将缩减,与中心区域显着不同。

采用这种方法的图像分割已经能够较为精确的将人脸和非人脸分割开来。

人脸识别流程图2.人脸识别程序(1)人脸和非人脸区域分割程序function result = skin(Y,Cb,Cr)%SKIN Summary of this function goes here% Detailed explanation goes herea=25.39;b=14.03;ecx=1.60;ecy=2.41;sita=2.53;cx=109.38;cy=152.02;xishu=[cos(sita) sin(sita);-sin(sita) cos(sita)];%如果亮度大于230,则将长短轴同时扩大为原来的1.1倍if(Y>230)a=1.1*a;b=1.1*b;end%根据公式进行计算Cb=double(Cb);Cr=double(Cr);t=[(Cb-cx);(Cr-cy)];temp=xishu*t;value=(temp(1)-ecx)^2/a^2+(temp(2)-ecy)^2/b^2;%大于1则不是肤色,返回0;否则为肤色,返回1if value>1result=0;elseresult=1;endend(2)人脸的确认程序function eye = findeye(bImage,x,y,w,h)%FINDEYE Summary of this function goes here % Detailed explanation goes herepart=zeros(h,w);%二值化for i=y:(y+h)for j=x:(x+w)if bImage(i,j)==0part(i-y+1,j-x+1)=255;elsepart(i-y+1,j-x+1)=0;endendend[L,num]=bwlabel(part,8);%如果区域中有两个以上的矩形则认为有眼睛if num<2eye=0;elseeye=1;endend(3)人脸识别主程序clear all;%读入原始图像I=imread('face3.jpg');gray=rgb2gray(I);ycbcr=rgb2ycbcr(I);%将图像转化为YCbCr空间heighth=size(gray,1);%读取图像尺寸width=size(gray,2);for i=1:heighth %利用肤色模型二值化图像for j=1:widthY=ycbcr(i,j,1);Cb=ycbcr(i,j,2);Cr=ycbcr(i,j,3);if(Y<80)gray(i,j)=0;elseif(skin(Y,Cb,Cr)==1)%根据色彩模型进行图像二值化gray(i,j)=255;elsegray(i,j)=0;endendendendse=strel('arbitrary',eye(5));%二值图像形态学处理gray=imopen(gray,se);figure;imshow(gray)[L,num]=bwlabel(gray,8);%采用标记方法选出图中的白色区域stats=regionprops(L,'BoundingBox');%度量区域属性n=1;%存放经过筛选以后得到的所有矩形块result=zeros(n,4);figure,imshow(I);hold on;for i=1:num %开始筛选特定区域box=stats(i).BoundingBox;x=box(1);%矩形坐标Xy=box(2);%矩形坐标Yw=box(3);%矩形宽度wh=box(4);%矩形高度hratio=h/w;%宽度和高度的比例ux=uint16(x);uy=uint8(y);if ux>1ux=ux-1;endif uy>1uy=uy-1;endif w<20 || h<20|| w*h<400 %矩形长宽的范围和矩形的面积可自行设定continueelseif ratio<2 && ratio>0.6 && findeye(gray,ux,uy,w,h)==1%根据“三庭五眼”规则高度和宽度比例应该在(0.6,2)内;result(n,:)=[ux uy w h];n=n+1;endendif size(result,1)==1 && result(1,1)>0 %对可能是人脸的区域进行标记rectangle('Position',[result(1,1),result(1,2),result(1,3),result(1,4)],'EdgeColor','r'); else%如果满足条件的矩形区域大于1,则再根据其他信息进行筛选a=0;arr1=[];arr2=[];for m=1:size(result,1)m1=result(m,1);m2=result(m,2);m3=result(m,3);m4=result(m,4);%得到符合和人脸匹配的数据if m1+m3<width && m2+m4<heighth && m3<0.2*width a=a+1;arr1(a)=m3;arr2(a)=m4;%rectangle('Position',[m1,m2,m3,m4],'EdgeColor','r');endend%得到人脸长度和宽度的最小区域arr3=[];arr3=sort(arr1,'ascend');arr4=[];arr4=sort(arr2,'ascend');%根据得到的数据标定最终的人脸区域for m=1:size(result,1)m1=result(m,1);m2=result(m,2);m3=result(m,3);m4=result(m,4);%最终标定人脸if m1+m3<width && m2+m4<heighth && m3<0.2*widthm3=arr3(1);m4=arr4(1);rectangle('Position',[m1,m2,m3,m4],'EdgeColor','r');endendend(4)程序说明人脸识别程序主要包含三个程序模块,人脸识别主程序由三部分构成。

基于MATLAB的人脸识别源程序文件

基于MATLAB的人脸识别源程序文件

1.色彩空间转换function [r,g]=rgb_RGB(Ori_Face)R=Ori_Face(:,:,1);G=Ori_Face(:,:,2);B=Ori_Face(:,:,3);R1=im2double(R); % 将uint8型转换成double型G1=im2double(G);B1=im2double(B);RGB=R1+G1+B1;row=size(Ori_Face,1); % 行像素column=size(Ori_Face,2); % 列像素for i=1:rowfor j=1:columnrr(i,j)=R1(i,j)/RGB(i,j);gg(i,j)=G1(i,j)/RGB(i,j);endendrrr=mean(rr);r=mean(rrr);ggg=mean(gg);g=mean(ggg);2.均值和协方差t1=imread('D:\matlab\皮肤库\1.jpg');[r1,g1]=rgb_RGB(t1);t2=imread('D:\matlab\皮肤库\2.jpg');[r2,g2]=rgb_RGB(t2);t3=imread('D:\matlab\皮肤库\3.jpg');[r3,g3]=rgb_RGB(t3);t4=imread('D:\matlab\皮肤库\4.jpg');[r4,g4]=rgb_RGB(t4);t5=imread('D:\matlab\皮肤库\5.jpg');[r5,g5]=rgb_RGB(t5);t6=imread('D:\matlab\皮肤库\6.jpg');[r6,g6]=rgb_RGB(t6);t7=imread('D:\matlab\皮肤库\7.jpg');[r7,g7]=rgb_RGB(t7);t8=imread('D:\matlab\皮肤库\8.jpg');[r8,g8]=rgb_RGB(t8);t9=imread('D:\matlab\皮肤库\9.jpg');[r9,g9]=rgb_RGB(t9);t10=imread('D:\matlab\皮肤库\10.jpg');[r10,g10]=rgb_RGB(t10);t11=imread('D:\matlab\皮肤库\11.jpg');[r11,g11]=rgb_RGB(t11);t12=imread('D:\matlab\皮肤库\12.jpg');[r12,g12]=rgb_RGB(t12);t13=imread('D:\matlab\皮肤库\13.jpg');[r13,g13]=rgb_RGB(t13);t14=imread('D:\matlab\皮肤库\14.jpg');[r14,g14]=rgb_RGB(t14);t15=imread('D:\matlab\皮肤库\15.jpg');[r15,g15]=rgb_RGB(t15);t16=imread('D:\matlab\皮肤库t17=imread('D:\matlab\皮肤库\17.jpg');[r17,g17]=rgb_RGB(t17);t18=imread('D:\matlab\皮肤库\18.jpg');[r18,g18]=rgb_RGB(t18);t19=imread('D:\matlab\皮肤库\19.jpg');[r19,g19]=rgb_RGB(t19);t20=imread('D:\matlab\皮肤库\20.jpg');[r20,g20]=rgb_RGB(t20);t21=imread('D:\matlab\皮肤库\21.jpg');[r21,g21]=rgb_RGB(t21);t22=imread('D:\matlab\皮肤库\22.jpg');[r22,g22]=rgb_RGB(t22);t23=imread('D:\matlab\皮肤库\23.jpg');[r23,g23]=rgb_RGB(t23);t24=imread('D:\matlab\皮肤库\24.jpg');[r24,g24]=rgb_RGB(t24);t25=imread('D:\matlab\皮肤库\25.jpg');[r25,g25]=rgb_RGB(t25);t26=imread('D:\matlab\皮肤库\26.jpg');[r26,g26]=rgb_RGB(t26);t27=imread('D:\matlab\皮肤库r=cat(1,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15, r16,r17,r18,r19,r20,r21,r22,r23,r24,r25,r26,r27);g=cat(1,g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11,g12,g13,g14,g15, g16,g17,g18,g19,g20,g21,g22,g23,g24,g25,g26,g27);m=mean([r,g])n=cov([r,g])3.求质心function [xmean, ymean] = center(bw)bw=bwfill(bw,'holes');area = bwarea(bw);[m n] =size(bw);bw=double(bw);xmean =0; ymean = 0;for i=1:m,for j=1:n,xmean = xmean + j*bw(i,j);ymean = ymean + i*bw(i,j);end;end;if(area==0)xmean=0;ymean=0;elsexmean = xmean/area;ymean = ymean/area;xmean = round(xmean);ymean = round(ymean);end4. 求偏转角度function [theta] = orient(bw,xmean,ymean) [m n] =size(bw);bw=double(bw);a = 0;b = 0;c = 0;for i=1:m,for j=1:n,a = a + (j - xmean)^2 * bw(i,j);b = b + (j - xmean) * (i - ymean) * bw(i,j);c = c + (i - ymean)^2 * bw(i,j);end;end;b = 2 * b;theta = atan(b/(a-c))/2;theta = theta*(180/pi); % 从幅度转换到角度5. 找区域边界function [left, right, up, down] = bianjie(A) [m n] = size(A);left = -1;right = -1;up = -1;down = -1;for j=1:n,for i=1:m,if (A(i,j) ~= 0)left = j;break;end;end;if (left ~= -1) break;end;end;for j=n:-1:1,for i=1:m,if (A(i,j) ~= 0)right = j;break;end;end;if (right ~= -1) break; end;end;for i=1:m,for j=1:n,if (A(i,j) ~= 0)up = i;break;end;end;if (up ~= -1)break;end;end;for i=m:-1:1,for j=1:n,if (A(i,j) ~= 0) down = i;break;end;end;if (down ~= -1)break;end;end;6. 求起始坐标function newcoord = checklimit(coord,maxval)newcoord = coord;if (newcoord<1)newcoord=1;end;if (newcoord>maxval)newcoord=maxval;end;7.模板匹配function [ccorr, mfit, RectCoord] = mobanpipei(mult, frontalmodel,ly,wx,cx, cy, angle)frontalmodel=rgb2gray(frontalmodel);model_rot = imresize(frontalmodel,[ly wx],'bilinear'); % 调整模板大小model_rot = imrotate(model_rot,angle,'bilinear'); % 旋转模板[l,r,u,d] = bianjie(model_rot); % 求边界坐标bwmodel_rot=imcrop(model_rot,[l u (r-l) (d-u)]); % 选择模板人脸区域[modx,mody] =center(bwmodel_rot); % 求质心[morig, norig] = size(bwmodel_rot);% 产生一个覆盖了人脸模板的灰度图像mfit = zeros(size(mult));mfitbw = zeros(size(mult));[limy, limx] = size(mfit);% 计算原图像中人脸模板的坐标startx = cx-modx;starty = cy-mody;endx = startx + norig-1;endy = starty + morig-1;startx = checklimit(startx,limx);starty = checklimit(starty,limy);endx = checklimit(endx,limx);endy = checklimit(endy,limy);for i=starty:endy,for j=startx:endx,mfit(i,j) = model_rot(i-starty+1,j-startx+1);end;end;ccorr = corr2(mfit,mult) % 计算相关度[l,r,u,d] = bianjie(bwmodel_rot);sx = startx+l;sy = starty+u;RectCoord = [sx sy (r-1) (d-u)]; % 产生矩形坐标8.主程序clear;[fname,pname]=uigetfile({'*.jpg';'*.bmp';'*.tif';'*.gif'},' Please choose a color picture...'); % 返回打开的图片名与图片路径名[u,v]=size(fname);y=fname(v); % 图片格式代表值switch ycase 0errordlg('You Should Load Image File First...','Warning...');case{'g';'G';'p';'P';'f';'F'}; % 图片格式若是JPG/jpg、BMP/bmp、TIF/tif或者GIF/gif,才打开I=cat(2,pname,fname);Ori_Face=imread(I);subplot(2,3,1),imshow(Ori_Face);otherwiseerrordlg('You Should Load Image File First...','Warning...');endR=Ori_Face(:,:,1);G=Ori_Face(:,:,2);B=Ori_Face(:,:,3);R1=im2double(R); % 将uint8型转换成double型处理G1=im2double(G);B1=im2double(B);RGB=R1+G1+B1;m=[ 0.4144,0.3174]; % 均值n=[0.0031,-0.0004;-0.0004,0.0003]; % 方差row=size(Ori_Face,1); % 行像素数column=size(Ori_Face,2); % 列像素数for i=1:rowfor j=1:columnif RGB(i,j)==0rr(i,j)=0;gg(i,j)=0;elserr(i,j)=R1(i,j)/RGB(i,j); % rgb归一化 gg(i,j)=G1(i,j)/RGB(i,j);x=[rr(i,j),gg(i,j)];p(i,j)=exp((-0.5)*(x-m)*inv(n)*(x-m)'); % 皮肤概率服从高斯分布endendendsubplot(2,3,2);imshow(p); % 显示皮肤灰度图像low_pass=1/9*ones(3);image_low=filter2(low_pass, p); % 低通滤波去噪声subplot(2,3,3);imshow(image_low);% 自适应阀值程序previousSkin2 = zeros(i,j);changelist = [];for threshold = 0.55:-0.1:0.05two_value = zeros(i,j);two_value(find(image_low>threshold)) = 1;change = sum(sum(two_value - previousSkin2));changelist = [changelist change];previousSkin2 = two_value;end[C, I] = min(changelist);optimalThreshold = (7-I)*0.1two_value = zeros(i,j);two_value(find(image_low>optimalThreshold)) = 1; % 二值化subplot(2,3,4);imshow(two_value); % 显示二值图像frontalmodel=imread('E:\我的照片\人脸模板.jpg'); % 读入人脸模板照片FaceCoord=[];imsourcegray=rgb2gray(Ori_Face); % 将原照片转换为灰度图像[L,N]=bwlabel(two_value,8); % 标注二值图像中连接的部分,L 为数据矩阵,N为颗粒的个数for i=1:N,[x,y]=find(bwlabel(two_value)==i); % 寻找矩阵中标号为i的行和列的下标bwsegment = bwselect(two_value,y,x,8); % 选择出第i个颗粒numholes = 1-bweuler(bwsegment,4); % 计算此区域的空洞数if (numholes >= 1) % 若此区域至少包含一个洞,则将其选出进行下一步运算RectCoord = -1;[m n] = size(bwsegment);[cx,cy]=center(bwsegment); % 求此区域的质心bwnohole=bwfill(bwsegment,'holes'); % 将洞封住(将灰度值赋为1)justface = uint8(double(bwnohole) .* double(imsourcegray)); % 只在原照片的灰度图像中保留该候选区域angle = orient(bwsegment,cx,cy); % 求此区域的偏转角度bw = imrotate(bwsegment, angle, 'bilinear');bw = bwfill(bw,'holes');[l,r,u,d] =bianjie(bw);wx = (r - l +1); % 宽度ly = (d - u + 1); % 高度wratio = ly/wx % 高宽比if ((0.8<=wratio)&(wratio<=2))% 如果目标区域的高度/宽度比例大于0.8且小于2.0,则将其选出进行下一步运算S=ly*wx; % 计算包含此区域矩形的面积A=bwarea(bwsegment); % 计算此区域面积if (A/S>0.35)[ccorr,mfit, RectCoord] = mobanpipei(justface,frontalmodel,ly,wx, cx,cy, angle);endif (ccorr>=0.6)mfitbw=(mfit>=1);invbw = xor(mfitbw,ones(size(mfitbw)));source_with_hole = uint8(double(invbw) .* double(imsourcegray));final_image = uint8(double(source_with_hole) + double(mfit));subplot(2,3,5);imshow(final_image); % 显示覆盖了模板脸的灰度图像imsourcegray = final_image;subplot(2,3,6);imshow(Ori_Face); % 显示检测效果图end;if (RectCoord ~= -1)FaceCoord = [FaceCoord; RectCoord];endendendend% 在认为是人脸的区域画矩形[numfaces x] = size(FaceCoord);for i=1:numfaces,hd = rectangle('Position',FaceCoord(i,:));set(hd, 'edgecolor', 'y');end人脸检测是人脸识别、人机交互、智能视觉监控等工作的前提。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

main
close all
clear all
clc
%输入图像名字
img_name=input('请输入图像名字(图像必须为RGB图像,输入0结束):','s');
%当输入0时结束
while~strcmp(img_name,'0')
%进行人脸识别
facedetection(img_name);
img_name=input('请输入图像名字(图像必须为RGB图像,输入0结束):','s'); end
facedetection
function facedetection(img_name)
%读取RGB图像
I=imread(img_name);
%转换为灰度图像
gray=rgb2gray(I);
%将图像转化为YCbCr颜色空间
YCbCr=rgb2ycbcr(I);
%获得图像宽度和高度
heigth=size(gray,1);
width=size(gray,2);
%根据肤色模型将图像二值化
for i=1:heigth
for j=1:width
Y=YCbCr(i,j,1);
Cb=YCbCr(i,j,2);
Cr=YCbCr(i,j,3);
if(Y<80)
gray(i,j)=0;
else
if(skin(Y,Cb,Cr)==1)
gray(i,j)=255;
else
gray(i,j)=0;
end
end
end
end
%二值图像形态学处理
SE=strel('arbitrary',eye(5));
%gray=bwmorph(gray,'erode');
%imopen先腐蚀再膨胀
gray=imopen(gray,SE);
%imclose先膨胀再腐蚀
%gray=imclose(gray,SE);
imshow(gray);
%取出图片中所有包含白色区域的最小矩形
[L,num]=bwlabel(gray,8);
STATS=regionprops(L,'BoundingBox');
%存放经过筛选以后得到的所有矩形块
n=1;
result=zeros(n,4);
figure,imshow(I);
hold on;
for i=1:num
box=STATS(i).BoundingBox;
x=box(1);%矩形坐标x
y=box(2);%矩形坐标y
w=box(3);%矩形宽度w
h=box(4);%矩形高度h
%宽度和高度的比例
ratio=h/w;
ux=uint8(x);
uy=uint8(y);
if ux>1
ux=ux-1;
end
if uy>1
uy=uy-1;
end
%可能是人脸区域的矩形应满足以下条件:
%1、高度和宽度必须都大于20,且矩形面积大于400 %2、高度和宽度比率应该在范围(0.6,2)内
%3、函数findeye返回值为1
if w<20||h<20||w*h<400
continue
elseif ratio<2&&ratio>0.6&&findeye(gray,ux,uy,w,h)==1 %记录可能为人脸的矩形区域
result(n,:)=[ux uy w h];
n=n+1;
end
end
%对可能是人脸的区域进行标记
if size(result,1)==1&&result(1,1)>0
rectangle('Position',[result(1,1),result(1,2),result(1,3),result(1,4)],'EdgeColor','r'); else
%如果满足条件的矩形区域大于1则再根据其他信息进行筛选
for m=1:size(result,1)
m1=result(m,1);
m2=result(m,2);
m3=result(m,3);
m4=result(m,4);
%标记最终的人脸区域
if m1+m3<width&&m2+m4<heigth
rectangle('Position',[m1,m2,m3,m4],'EdgeColor','r');
end
end
end
findeye
%判断二值图像中是否含有可能是眼睛的块
%bImage----二值图像
%x---------矩形左上角顶点X坐标
%y---------矩形左上角顶点Y坐标
%w---------矩形宽度
%h---------矩形长度
%如果有则返回值eye等于1,否则为0
function eye=findeye(bImage,x,y,w,h)
%根据矩形相关属性得到二值图像中矩形区域中的数据
%存放矩形区域二值图像信息
part=zeros(h,w);
%二值化
for i=y:(y+h)
for j=x:(x+w)
if bImage(i,j)==0
part(i-y+1,j-x+1)=255;
else
part(i-y+1,j-x+1)=0;
end
end
end
[L,num]=bwlabel(part,8);
%如果区域中有两个以上的矩形则认为有眼睛
if num<2
eye=0;
else
eye=1;
end
skin
%Anil K.Jain提出的基于YCbCr颜色空间的肤色模型
%根据当前点的Cb Cr值判断是否为肤色
function result=skin(Y,Cb,Cr)
%参数
%a=25.39;
a=28;
%b=14.03;
b=18;
ecx=1.60;
ecy=2.41;
sita=2.53;
cx=109.38;
cy=152.02;
xishu=[cos(sita)sin(sita);-sin(sita)cos(sita)];
%如果亮度大于230,则将长短轴同时扩大为原来的1.1倍if(Y>230)
a=1.1*a;
b=1.1*b;
end
%根据公式进行计算
Cb=double(Cb);
Cr=double(Cr);
t=[(Cb-cx);(Cr-cy)];
temp=xishu*t;
value=(temp(1)-ecx)^2/a^2+(temp(2)-ecy)^2/b^2;
%大于1则不是肤色,返回0;否则为肤色,返回1
if value>1
result=0;
else
result=1;
end。

相关文档
最新文档