使用adaboost+haar分類器檢測車輛demo
阿新 • • 發佈:2019-01-06
程式碼如下
#include <iostream>
#include <opencv2/opencv.hpp>
#include <string>
using namespace std;
using namespace cv;
CascadeClassifier car_classifier;
string cascade_name = "car.xml";
void detect_and_display(Mat car,string video_windows_name);//////檢測和顯示函式
int main()
{
VideoCapture cap;
cap.open("car.avi" );
if(!cap.isOpened())
{
cout<<"the video is not opened......."<<endl;
return -1;
}
if(!car_classifier.load(cascade_name.c_str()))
{
cout<<"分類器匯入失敗"<<endl;
return -1;
}
while(1)
{
Mat frame;
cap>>frame;
//imshow("frame",frame);
//waitKey(33);
if(frame.data)
detect_and_display(frame,"detect_and_display");
}
return 0;
}
void detect_and_display(Mat car,string video_windows_name)
{
std::vector<Rect> cars;
Mat car_gray, small_img;
double scale = 1.3;
Point pt11, pt22;
cvtColor(car, car_gray, CV_BGR2GRAY); //rgb型別轉換為灰度型別
resize(car_gray, small_img, Size(cvRound(car_gray.cols / scale), cvRound(car_gray.rows / scale)), 0, 0, CV_INTER_LINEAR);
equalizeHist(small_img, small_img); //直方圖均衡化
car_classifier.detectMultiScale(small_img,
cars,
1.1,
3,
CV_HAAR_DO_CANNY_PRUNING,
Size(20, 20));
for (int i = 0; i < cars.size(); i++)
{
Point pt11,pt22;
pt11.x = cars[i].x*scale;
pt22.x = (cars[i].x + cars[i].width)*scale;
pt11.y = cars[i].y*scale;
pt22.y = (cars[i].y + cars[i].height)*scale;
rectangle(car, pt11, pt22, CV_RGB(255, 255, 0), 2, 8, 0);
}
imshow(video_windows_name,car);
waitKey(33);
}