delphi xe OpenCV 人脸对比 代码
时间: 2023-09-09 19:06:26 浏览: 151
以下是 Delphi XE 和 OpenCV 实现人脸对比的示例代码:
```delphi
uses
..., cvtypes, cvimgproc, cvobjdetect, cvface;
procedure TForm1.CompareFaces(const Image1, Image2: IplImage);
var
FaceRecognizer: TCvFaceRecognizer;
FaceRecognizerType: TCvFaceRecognizerType;
FaceDetector: TCvHaarClassifierCascade;
Storage: PCvMemStorage;
Faces1, Faces2: PCvSeq;
Face1, Face2: PCvRect;
Gray1, Gray2: IplImage;
FaceImage1, FaceImage2: IplImage;
FaceFeature1, FaceFeature2: PSingle;
Distance: Single;
begin
// 初始化人脸检测器
FaceDetector := cvLoadHaarClassifierCascade('haarcascade_frontalface_alt.xml', cvSize(0, 0));
// 初始化人脸识别器
FaceRecognizerType := cvFaceRecognizerLBPH;
FaceRecognizer := cvCreateFaceRecognizer(FaceRecognizerType);
// 初始化特征存储器
Storage := cvCreateMemStorage(0);
// 加载图像并进行灰度化
Gray1 := cvCreateImage(Image1.cvSize, Image1.depth, 1);
cvCvtColor(Image1, Gray1, CV_BGR2GRAY);
Gray2 := cvCreateImage(Image2.cvSize, Image2.depth, 1);
cvCvtColor(Image2, Gray2, CV_BGR2GRAY);
try
// 检测人脸
Faces1 := cvHaarDetectObjects(Gray1, FaceDetector, Storage, 1.2, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(30, 30));
Faces2 := cvHaarDetectObjects(Gray2, FaceDetector, Storage, 1.2, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(30, 30));
// 获取第一个人脸的图像并进行特征提取
if (Faces1 <> nil) and (Faces1^.total > 0) then
begin
Face1 := PCvRect(cvGetSeqElem(Faces1, 0));
FaceImage1 := cvCreateImage(cvSize(Face1^.width, Face1^.height), Image1.depth, Image1.nChannels);
cvSetImageROI(Image1, cvRect(Face1^.x, Face1^.y, Face1^.width, Face1^.height));
cvCopy(Image1, FaceImage1, nil);
cvResetImageROI(Image1);
FaceFeature1 := cvCreateMat(1, FaceRecognizer.eigenVects^.cols, CV_32FC1);
cvExtractFaceFeature(FaceImage1, FaceFeature1, FaceRecognizer);
end;
// 获取第二个人脸的图像并进行特征提取
if (Faces2 <> nil) and (Faces2^.total > 0) then
begin
Face2 := PCvRect(cvGetSeqElem(Faces2, 0));
FaceImage2 := cvCreateImage(cvSize(Face2^.width, Face2^.height), Image2.depth, Image2.nChannels);
cvSetImageROI(Image2, cvRect(Face2^.x, Face2^.y, Face2^.width, Face2^.height));
cvCopy(Image2, FaceImage2, nil);
cvResetImageROI(Image2);
FaceFeature2 := cvCreateMat(1, FaceRecognizer.eigenVects^.cols, CV_32FC1);
cvExtractFaceFeature(FaceImage2, FaceFeature2, FaceRecognizer);
end;
// 计算人脸相似度
if (FaceFeature1 <> nil) and (FaceFeature2 <> nil) then
begin
Distance := cvNorm(FaceFeature1, FaceFeature2, CV_L2);
if Distance < 0.6 then
ShowMessage('两张人脸相似')
else
ShowMessage('两张人脸不相似');
end;
finally
// 释放资源
cvReleaseHaarClassifierCascade(FaceDetector);
cvReleaseMemStorage(Storage);
cvReleaseImage(Gray1);
cvReleaseImage(Gray2);
if FaceImage1 <> nil then
cvReleaseImage(FaceImage1);
if FaceImage2 <> nil then
cvReleaseImage(FaceImage2);
if FaceFeature1 <> nil then
cvReleaseMat(FaceFeature1);
if FaceFeature2 <> nil then
cvReleaseMat(FaceFeature2);
end;
end;
```
上述代码中,使用了 OpenCV 的人脸检测器和人脸识别器进行人脸对比。具体实现细节可以参考 OpenCV 的相关文档和示例代码。
阅读全文