delphixe opencv 人脸识别代码
时间: 2023-06-28 09:16:23 浏览: 186
opencv 人脸识别 代码
4星 · 用户满意度95%
以下是一个简单的DelphiXE中使用OpenCV进行人脸识别的示例代码:
```delphi
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Vcl.Imaging.jpeg, Vcl.Imaging.pngimage,
cv_types, cv_highgui, cv_objdetect;
type
TForm1 = class(TForm)
Image1: TImage;
Button1: TButton;
OpenDialog1: TOpenDialog;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
const
haarcascadeFile = 'haarcascade_frontalface_default.xml';
var
face: IplImage;
storage: pCvMemStorage;
cascade: pCvHaarClassifierCascade;
i: Integer;
s: string;
begin
if OpenDialog1.Execute then
begin
// 加载人脸检测分类器
cascade := cvLoadHaarClassifierCascade(haarcascadeFile, cvSize(0, 0));
if cascade = nil then
begin
ShowMessage('无法加载人脸检测分类器');
Exit;
end;
// 加载图像
face := cvLoadImage(PAnsiChar(AnsiString(OpenDialog1.FileName)),
CV_LOAD_IMAGE_COLOR);
if face = nil then
begin
ShowMessage('无法加载图像');
Exit;
end;
// 创建存储器
storage := cvCreateMemStorage(0);
// 识别人脸
cvClearMemStorage(storage);
cvEqualizeHist(face, face);
cascade := cvLoadHaarClassifierCascade(haarcascadeFile, cvSize(0, 0));
CvSeq := cvHaarDetectObjects(face, cascade, storage, 1.2, 2,
CV_HAAR_DO_CANNY_PRUNING, cvSize(30, 30), cvSize(0, 0));
for i := 0 to CvSeq.total - 1 do
begin
// 在图像中框出人脸
s := '人脸 ' + IntToStr(i + 1);
cvRectangle(face, cvPoint(CvRect(CvRect(CvSeq^.rect)[i]).x,
CvRect(CvRect(CvSeq^.rect)[i]).y),
cvPoint(CvRect(CvRect(CvSeq^.rect)[i]).x + CvRect(CvRect(CvSeq^.rect)
[i]).width, CvRect(CvRect(CvSeq^.rect)[i]).y + CvRect(CvRect(CvSeq^.rect)
[i]).height), CV_RGB(0, 255, 0), 3, 8, 0);
end;
// 显示图像
Image1.Picture.Bitmap.Assign(IplImageToBitmap(face));
// 释放资源
cvReleaseHaarClassifierCascade(cascade);
cvReleaseImage(face);
cvClearMemStorage(storage);
cvReleaseMemStorage(@storage);
end;
end;
end.
```
注意:代码中的`haarcascade_frontalface_default.xml`是OpenCV库中自带的人脸检测分类器文件,需要放置在与程序同一目录下。如果需要使用其他的分类器文件,可以将其拷贝到程序目录下并修改代码中的文件名。
阅读全文