加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
carDetect.cpp 2.71 KB
一键复制 编辑 原始数据 按行查看 历史
root 提交于 2021-03-25 16:38 . dd
#include "opencv2/highgui.hpp"
#include "opencv2/objdetect.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
using namespace std;
using namespace cv;
static void help(const char** argv);
void detectAndDraw(Mat & img, CascadeClassifier & cascade);
Mat getFrameByCap();
Mat getImage(string path);
int main(int argc,const char * argv[])
{
VideoCapture cap;
//help(argv);
Mat frame1,frame2;
cv::CommandLineParser parser(argc, argv,
"{help||}"
"{cascade|./train/train_result/cascade.xml|}"
"{video|-1|}"
"{@filename||}"
);
if(parser.has("help"))
{
help(argv);
return 0;
}
CascadeClassifier cascade;
string cascadeName = parser.get<string>("cascade");
int isVideo = parser.get<int>("video");
string car_pic_path = parser.get<string>("@filename");
if (!parser.check())
{
parser.printErrors();
return 0;
}
//加载汽车模型
if (!cascade.load(samples::findFile(cascadeName)))
{
cerr << "错误:找不到目标模型" << endl;
help(argv);
return -1;
}
if(isVideo == -1){
Mat img = getImage(car_pic_path);
detectAndDraw(img,cascade);
while(true)
{
char c = (char)waitKey(8);
if (c == 25 || c == 'q' || c == 'Q')
break;
}
return 0;
}
//open capture
try{
cap.open(isVideo);
}catch(cv::Exception e){
cout << "video device cannot work correctly"<<endl;
return -1;
}
if(cap.isOpened()){
for(;;)
{
cap >> frame1;
frame2 = frame1.clone();
if(frame2.empty())
{
break;
}
detectAndDraw(frame2,cascade);
//将图片显示在屏幕上
char c = (char)waitKey(8);
if (c == 25 || c == 'q' || c == 'Q')
break;
}
}
return 0;
}
static void help(const char** argv)
{
cout << "\n车辆检测程序\n"
"Usage:\n"
<< argv[0]
<< " [--cascade=<cascade_path> 车辆检测模型]\n"
" [--video=1 use video capture device 1]\n"
"[<filename> detect img if video was not given]\n"
"example:\n"
<< argv[0]
<< " --cascade=\"data/train/train_result/cascade.xml\" --video=1\n"
"\n\n——————Using OpenCV version " << CV_VERSION << "——————\n" << endl;
}
void detectAndDraw(Mat & img, CascadeClassifier & cascade)
{
Mat frame_gray;
cvtColor(img,frame_gray,COLOR_BGR2GRAY);
equalizeHist(frame_gray,frame_gray);
vector<Rect> cars;
//detect
cascade.detectMultiScale(frame_gray,cars);
//rectangle
for(size_t i =0;i<cars.size();i++)
rectangle(img,cars[i],Scalar(255,0,0));
imshow("检测结果",img);
}
Mat getFrameByCap()
{
}
Mat getImage(string path)
{
//读取待检测图片
Mat car_pic;
try{
car_pic = imread(samples::findFileOrKeep(path));
}catch(cv::Exception e){
cerr << "错误:找不到待检测图片" << endl;
}
return car_pic;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化