废话不多说上代码(opencv 3.4.16 vs v141 win32):
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs/imgcodecs.hpp>
#include <opencv2/opencv.hpp>
#include <vector>
#include <cstdio>
#include<opencv2/highgui.hpp>
#include<opencv2/imgcodecs.hpp>
#include<opencv2/opencv.hpp>
#include<Windows.h>
using namespace std;
using namespace cv;
//读取训练器,这里用的是haar路径在你下载的opencv中
CascadeClassifier cascade;
String haarfile = "F://haarcascades//haarcascade_frontalface_alt2.xml";
int main() {
if (!cascade.load(haarfile))
{
printf("不能加载指定的xml文件\n");
return -1;
}
VideoCapture cap(0);
Mat srcImage, grayImage, dstImage;
Scalar colors[] = {
//红橙黄绿青蓝紫
CV_RGB(255, 0, 0),
CV_RGB(255, 97, 0),
CV_RGB(255, 255, 0),
CV_RGB(0, 255, 0),
CV_RGB(0, 255, 255),
CV_RGB(0, 0, 255),
CV_RGB(160, 32, 240)
};
while (true)
{
cap.read(srcImage);
dstImage = srcImage.clone();
cvtColor(srcImage, grayImage, COLOR_BGR2GRAY);
//imshow("Image2", grayImage);
//imshow("Image", srcImage);
vector<Rect> rect;
cascade.detectMultiScale(grayImage, rect, 1.1, 3, 0);
for (int i = 0; i < rect.size(); i++)
{
Point center;
int radius;
center.x = cvRound(rect[i].x + rect[i].width*0.5);
center.y = cvRound(rect[i].y + rect[i].height*0.5);
radius = cvRound((rect[i].width + rect[i].height)*0.25);
circle(dstImage, center, radius, colors[i % 7], 2);
}
imshow("Image3", dstImage);
waitKey(1);
}
return 0;
}
其中载入这个haarcascade_frontalface_alt2.xml文件的路径格式需要注意,如果我的代码格式不适用,你多试集中,不一定是训练文件本身的问题,而是路径格式的问题.