级联分类器的介绍
级联分类器是一种用于对象检测的机器学习算法,它通过级联的方式对图像进行多次分类,从而实现高效的目标检测。在本文档中,我们将介绍如何使用级联分类器进行目标检测,并提供相关的代码示例。
级联分类器的使用
当我们训练完自己的级联分类器之后,便可以使用它去做一个检测,一下是车辆检测的级联分类器的使用代码:
#include <iostream>
#include <opencv2/opencv.hpp>
#include <vector>
using namespace std;
using namespace cv;
//级联分类器车辆检测函数
void detectCarDraw(Mat &frame,CascadeClassifier &cascade,double scale)
{
//1:灰度处理 压缩到原来图片的三分之一
Mat gray;
cvtColor(frame,gray,CV_BGR2GRAY);
//2:灰度处理后的帧画面缩小到原来的一半
//设置了尺寸
Mat smalling(cvRound(frame.rows/scale),cvRound(frame.cols/scale),CV_8UC1);
//INTER_LINEAR等比例缩小
resize(gray,smalling,smalling.size(),0,0,INTER_LINEAR);
//3:直方图均衡化 画面线条更清晰
equalizeHist(smalling,smalling);
//4:级联分类器模型检测
vector<Rect>cars;
//检测存储
cascade.detectMultiScale(smalling,cars,1.1,2,0|CV_HAAR_SCALE_IMAGE,Size(30,30));
//5:绘制矩形框
vector <Rect>::const_iterator iter;
for(iter=cars.begin();iter!=cars.end();iter++)
{
rectangle(frame,
CvPoint(cvRound(iter->x*scale),cvRound(iter->y*scale)),
CvPoint(cvRound((iter->x+iter->width)*scale),cvRound((iter->y+iter->height)*scale)),
Scalar(0,255,0),2,8);
}
imshow("resFrame",frame);
}
int main()
{
//级联分类器加载级联分类器文件
CascadeClassifier cascade;
//读取
cascade.load("D:/zhuomian/cars.xml");
VideoCapture cap("D:/zhuomian/carMove.mp4");
Mat frame;
while(cap.read(frame))
{
//显示原画面
imshow("frame",frame);
//车辆检测
detectCarDraw(frame,cascade,2);
waitKey(40);
}
return 0;
}
级联分类器检测结果展示
右边是原视频,左边是检测后的视频