Matlab實現簡單的人臉識別程式
clear all;
close all;
F = imread(‘face9.jpg’);
F = rgb2gray(F); % 將影象轉化為灰度圖
level = graythresh(F);
BW = im2bw(F,level); % 將影象二值化
[n1 n2] = size(BW);
H = floor(n1/10); % 將影象分割成10個快
W = floor(n2/10);
h1 = 1;
h2 = H;
s = H*W; % 求得塊的面積
h_i = H;
w_i = W;
for i = 1:10
w1 = 1;w2 =W; % 對應列初始化
for j = 1:10
if (w1 <= w_i || w2 >= 9*W) || (h1 <= h_i || h2 >= n1 - h_i) % 判斷是否在圖片四周的區域
loc = find(BW(h1:h2,w1:w2) == 0)
[num,~] = size(loc);
pr = num*100/s; % 計算灰度為黑色的畫素佔的比例
if pr < 100
BW(h1:h2,w1:w2) = 0;
end
% figure,imshow(BW);
% hold on
end
w1 = w1+W; % 跳到下一個塊對應的列
w2 = w2+W;
end
h1 = h1+H; % 跳到下一個塊對應的行
h2 = h2+H;
end
L = bwlabel(BW,8); % 區域標記
BB = regionprops(L,’BoundingBox’); % 得到包圍的矩形框
Bd = cat(1,BB.BoundingBox);
[Bd_i,~] = size(Bd);
mx = 0;
for k = 1:Bd_i
p = Bd(k, 3)*Bd(k, 4);
% 如果滿足面積塊大,而且寬/高<1.8,則跳到Bd的該行
if p > mx && (Bd(k,3)/Bd(k,4)) < 1.8
mx = p;
j = k;
end
end
imshow(F); hold on; % 顯示圖片
% 畫出矩形框
rectangle(‘Position’, Bd(j, :), …
‘EdgeColor’, ‘r’, ‘LineWidth’, 3);
title(‘標記影象’, ‘FontWeight’, ‘Bold’);