delphi xe opencv 人脸识别代码
时间: 2023-06-30 15:11:59 浏览: 90
opencv 人脸识别 代码
4星 · 用户满意度95%
以下是基于 Delphi XE 和 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.ExtCtrls, Vcl.StdCtrls, Vcl.Imaging.jpeg,
OpenCV.Core, OpenCV.ImgProc, OpenCV.HighGUI, OpenCV.ObjDetect, OpenCV.Video;
type
TForm1 = class(TForm)
Image1: TImage;
Timer1: TTimer;
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
cascade: pCvHaarClassifierCascade;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
filename: string;
begin
// 加载人脸识别级联分类器
filename := 'haarcascade_frontalface_alt.xml';
cascade := cvLoadHaarClassifierCascade(PAnsiChar(AnsiString(filename)), cvSize(0, 0));
// 启动定时器
Timer1.Enabled := True;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
capture: pCvCapture;
frame: pIplImage;
gray: pIplImage;
storage: pCvMemStorage;
faces: pCvSeq;
i: Integer;
rect: TCvRect;
image: TBitmap;
begin
// 打开摄像头
capture := cvCreateCameraCapture(0);
try
// 获取一帧图像
frame := cvQueryFrame(capture);
if Assigned(frame) then
begin
// 转换为灰度图像
gray := cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 1);
try
cvCvtColor(frame, gray, CV_BGR2GRAY);
// 进行人脸识别
storage := cvCreateMemStorage(0);
try
faces := cvHaarDetectObjects(gray, cascade, storage, 1.2, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(50, 50));
try
// 在图像中绘制人脸矩形
image := TBitmap.Create;
try
image.Width := frame.width;
image.Height := frame.height;
cvCvtColor(frame, gray, CV_BGR2RGB);
image.Canvas.Draw(0, 0, image);
for i := 0 to faces.total - 1 do
begin
rect := pCvRect(cvGetSeqElem(faces, i))^;
image.Canvas.Brush.Style := bsClear;
image.Canvas.Pen.Color := clRed;
image.Canvas.Pen.Width := 2;
image.Canvas.Rectangle(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height);
end;
Image1.Picture.Bitmap.Assign(image);
finally
image.Free;
end;
finally
cvClearSeq(faces);
end;
finally
cvReleaseMemStorage(@storage);
end;
finally
cvReleaseImage(@gray);
end;
end;
finally
cvReleaseCapture(@capture);
end;
end;
end.
```
这个代码使用 Delphi XE 和 OpenCV,通过摄像头实时获取图像,进行人脸识别,并在图像中绘制人脸矩形。请注意,需要将 `haarcascade_frontalface_alt.xml` 文件放在同一目录下。
阅读全文