本文共 3438 字,大约阅读时间需要 11 分钟。
本文将详细介绍如何利用OpenCV库实现人脸检测和图像处理功能。通过本文的步骤指导,您可以轻松完成目标检测和图像分析任务。
在开始编写代码之前,确保您的开发环境已正确配置。以下是必要的软件版本:
创建一个新的项目文件夹,文件结构如下:
project├── src│ └── main.cpp└── build └── Debug └── main.exe
#include#include #include #include #include #include #include using namespace cv;using namespace std;void detectAndDraw(Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale, bool tryflip) { vector faces, faces2; const static Scalar colors[] = { CV_RGB(0,0,255), CV_RGB(0,128,255), CV_RGB(0,255,255), CV_RGB(0,255,0), CV_RGB(255,128,0), CV_RGB(255,255,0), CV_RGB(255,0,0), CV_RGB(255,0,255) }; Mat gray, smallImg(cvRound(img.rows / scale), cvRound(img.cols / scale), CV_8UC1); cvtColor(img, gray, CV_BGR2GRAY); resize(gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR); equalizeHist(smallImg, smallImg); cascade.detectMultiScale(smallImg, faces, 1.1, 2, 0, Size(30, 30)); if (tryflip) { flip(smallImg, smallImg, 1); cascade.detectMultiScale(smallImg, faces2, 1.1, 2, 0, Size(30, 30)); for (auto r : faces2.begin(), auto rEnd : faces2.end()) { faces.push_back(Rect(smallImg.cols - r->x - r->width, r->y, r->width, r->height)); } } for (auto r : faces.begin(), auto rEnd : faces.end()) { int i++; Point center; Scalar color = colors[i % 8]; double aspect_ratio = r.width / r.height; if (0.75 < aspect_ratio && aspect_ratio < 1.3) { center.x = cvRound((r.x + r.width * 0.5) * scale); center.y = cvRound((r.y + r.height * 0.5) * scale); int radius = cvRound((r.width + r.height) * 0.25 * scale); circle(img, center, radius, color, 3, 8, 0); } else { rectangle(img, Point(cvRound(r.x * scale), cvRound(r.y * scale)), Point(cvRound((r.x + r.width - 1) * scale), cvRound((r.y + r.height - 1) * scale)), color, 3, 8, 0); } Mat smallImgROI = smallImg(r); if (!nestedCascade.empty()) { vector nestedObjects; nestedCascade.detectMultiScale(smallImgROI, nestedObjects, 1.1, 2, 0, Size(30, 30)); for (auto nr : nestedObjects.begin(), auto nrEnd : nestedObjects.end()) { center.x = cvRound((r.x + nr.x + nr.width * 0.5) * scale); center.y = cvRound((r.y + nr.y + nr.height * 0.5) * scale); int radius = cvRound((nr.width + nr.height) * 0.25 * scale); circle(img, center, radius, color, 3, 8, 0); } } } imshow("识别结果", img);}int main() { CascadeClassifier cascade, nestedCascade; string cascade_path = "D:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml"; string nested_path = "D:/opencv/sources/data/haarcascades/haarcascade_eye.xml"; VideoCapture cap(0); if (!cap.isOpened()) { return -1; } Mat frame; namedWindow("输入图像", WINDOW_AUTOSIZE); while (true) { cap >> frame; detectAndDraw(frame, cascade, nestedCascade, 2, 0); if (waitKey(30) >= 0) { break; } } return 0;}
代码结构:代码主要包括两部分,detectAndDraw函数负责检测人脸和眼部,main函数负责程序的运行逻辑。
预处理步骤:
人脸检测:
detectMultiScale函数进行多尺度人脸检测。图像显示:使用imshow函数显示检测结果。
性能优化:通过计算算法执行时间,供开发和调试参考。
运行上述代码,您将看到以下结果:
VideoCapture读取图像,确保摄像头权限。通过本文的指导,您可以根据实际需求对OpenCV人脸检测和图像处理进行更深入的定制和优化。
转载地址:http://nlsfk.baihongyu.com/