delphi-opencv 人脸对比 代码
时间: 2023-06-30 17:12:07 浏览: 111
以下是使用 Delphi 和 OpenCV 库实现人脸对比的示例代码:
```
uses
cv, highgui;
function CompareFaces(const Img1Path, Img2Path: string): Double;
var
Img1, Img2: IplImage;
FaceCascade: pCvHaarClassifierCascade;
Storage: pCvMemStorage;
FaceRect1, FaceRect2: CvRect;
FaceImg1, FaceImg2: IplImage;
Hist1, Hist2: pCvHistogram;
begin
Result := 0.0;
// 加载图像
Img1 := cvLoadImage(PAnsiChar(AnsiString(Img1Path)), CV_LOAD_IMAGE_GRAYSCALE);
Img2 := cvLoadImage(PAnsiChar(AnsiString(Img2Path)), CV_LOAD_IMAGE_GRAYSCALE);
// 加载人脸识别器
FaceCascade := cvLoadHaarClassifierCascade(PAnsiChar(AnsiString('haarcascade_frontalface_alt.xml')), cvSize(0, 0));
// 创建内存存储器
Storage := cvCreateMemStorage(0);
try
// 检测人脸
FaceRect1 := cvHaarDetectObjects(Img1, FaceCascade, Storage, 1.2, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(30, 30));
FaceRect2 := cvHaarDetectObjects(Img2, FaceCascade, Storage, 1.2, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(30, 30));
// 如果检测到的人脸数量不为 1,则返回 0
if (FaceRect1.total <> 1) or (FaceRect2.total <> 1) then
Exit;
// 获取人脸图像
FaceImg1 := cvCreateImage(cvSize(FaceRect1.width, FaceRect1.height), IPL_DEPTH_8U, 1);
cvSetImageROI(Img1, FaceRect1);
cvCopy(Img1, FaceImg1, nil);
cvResetImageROI(Img1);
FaceImg2 := cvCreateImage(cvSize(FaceRect2.width, FaceRect2.height), IPL_DEPTH_8U, 1);
cvSetImageROI(Img2, FaceRect2);
cvCopy(Img2, FaceImg2, nil);
cvResetImageROI(Img2);
// 创建直方图
Hist1 := cvCreateHist(1, @256, CV_HIST_ARRAY, nil, 1);
Hist2 := cvCreateHist(1, @256, CV_HIST_ARRAY, nil, 1);
// 计算直方图
cvCalcHist(@FaceImg1, Hist1);
cvCalcHist(@FaceImg2, Hist2);
// 计算相似度
Result := cvCompareHist(Hist1, Hist2, CV_COMP_CORREL);
finally
// 释放资源
cvReleaseImage(@Img1);
cvReleaseImage(@Img2);
cvReleaseHaarClassifierCascade(FaceCascade);
cvReleaseMemStorage(@Storage);
cvReleaseImage(@FaceImg1);
cvReleaseImage(@FaceImg2);
cvReleaseHist(@Hist1);
cvReleaseHist(@Hist2);
end;
end;
```
该函数接受两个图像文件路径,返回它们之间的人脸相似度。请注意,该函数假定每个图像中只有一个人脸。如果图像中有多个人脸,则将返回 0。
阅读全文