opencv使用级联分类器实现图像识别功能的教程【Qt】

#include <openCV2/core.hpp> // OpenCV的核心功能,包括矩阵等基本数据结构
#include <openCV2/imgcodecs.hpp> // 图像编解码相关的功能
#include <openCV2/highgui.hpp> // 图形用户界面(GUI)相关的功能
#include <openCV2\opencv.hpp>
#include <iostream>
#include <vector>
#include <qthread.h>
#include <QtWidgets/QApplication>
using namespace cv;
using namespace std;
// 绘制矩形框在图像上
void DrawRect(Mat& src, vector<Rect>& object) {
if (object.empty()) {
return;
}
for (int i = 0; i < object.size(); i++) {
int x = object[i].tl().x; // 矩形框左上角 x 坐标
int y = object[i].tl().y; // 矩形框左上角 y 坐标
int w = object[i].width; // 矩形框宽度
int h = object[i].height; // 矩形框高度
// 如果矩形框的宽度或高度大于100像素,则不绘制
if (w > 100 || h > 100)
return;
// 绘制矩形框,使用红色颜色,线宽为6
rectangle(src, Rect(x, y, w, h), Scalar(255, 0, 0), 6);
}
}
// 显示视频并进行目标检测
void ShowVideo() {
VideoCapture cap("G:\\video\\qwe.mp4"); // 打开视频文件
if (!cap.isOpened()) {
cout << "视频打开失败" << endl;
return;
}
cout << "视频打开成功" << endl;
CascadeClassifier cascade; // 创建级联分类器对象
if (!cascade.load("G:\\img\\data\\cascade.xml")) { // 加载级联分类器的 XML 文件
cout << "级联分类器加载失败" << endl;
return;
}
cout << "级联分类器加载成功" << endl;
vector<Rect> rects;
Mat img;
while (cap.read(img)) // 读取视频帧
{
rects.clear();
cascade.detectMultiScale(img, rects); // 对图像进行目标检测,返回矩形框的位置
if (!rects.empty()) {
DrawRect(img, rects); // 绘制检测到的矩形框
imshow("video", img); // 显示带有矩形框的图像
}
QCoreApplication::processEvents(); // 处理Qt事件
QThread::msleep(30); // 等待30毫秒,控制视频播放速度
}
cap.release(); // 释放视频资源
return;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv); // 创建Qt应用程序对象
ShowVideo(); // 调用函数显示视频并进行目标检测
return a.exec(); // 运行Qt应用程序的事件循环
}