OpenCV 4.13.0
开源计算机视觉库 (Open Source Computer Vision)
正在加载...
正在搜索...
未找到匹配项
samples/cpp/facedetect.cpp

此程序演示了 CascadeClassifier 类的用法

示例截图
#include <iostream>
using namespace std;
using namespace cv;
static void help(const char** argv)
{
cout << "\n此程序演示了 cv::CascadeClassifier 类用于检测对象(面部 + 眼睛)。您可以使用 Haar 或 LBP 特征。\n"
"此分类器在训练好合适的分类器后,可以识别多种刚性对象。\n"
"它最广为人知的用途是识别面部。\n"
"Usage:\n"
<< argv[0]
<< " [--cascade=<级联文件路径> 这是主要训练分类器,例如正面人脸]\n"
" [--nested-cascade[=嵌套级联文件路径 这是可选的次要分类器,例如眼睛]]\n"
" [--scale=<图像缩放比例大于或等于 1,例如尝试 1.3>]\n"
" [--try-flip]\n"
" [文件名|摄像头索引]\n\n"
"示例:\n"
<< argv[0]
<< " --cascade=\"data/haarcascades/haarcascade_frontalface_alt.xml\" --nested-cascade=\"data/haarcascades/haarcascade_eye_tree_eyeglasses.xml\" --scale=1.3\n\n"
"执行过程中:\t按任意键退出。\n"
"\t正在使用 OpenCV 版本 " << CV_VERSION << "\n" << endl;
}
void detectAndDraw( Mat& img, CascadeClassifier& cascade,
CascadeClassifier& nestedCascade,
double scale, bool tryflip );
string cascadeName;
string nestedCascadeName;
int main( int argc, const char** argv )
{
VideoCapture capture;
Mat frame, image;
string inputName;
bool tryflip;
CascadeClassifier cascade, nestedCascade;
double scale;
cv::CommandLineParser parser(argc, argv,
"{help h||}"
"{cascade|data/haarcascades/haarcascade_frontalface_alt.xml|}"
"{nested-cascade|data/haarcascades/haarcascade_eye_tree_eyeglasses.xml|}"
"{scale|1|}{try-flip||}{@filename||}"
);
if (parser.has("help"))
{
help(argv);
return 0;
}
cascadeName = parser.get<string>("cascade");
nestedCascadeName = parser.get<string>("nested-cascade");
scale = parser.get<double>("scale");
if (scale < 1)
scale = 1;
tryflip = parser.has("try-flip");
inputName = parser.get<string>("@filename");
if (!parser.check())
{
parser.printErrors();
return 0;
}
if (!nestedCascade.load(samples::findFileOrKeep(nestedCascadeName)))
cerr << "警告:无法加载嵌套对象的分类器级联" << endl;
if (!cascade.load(samples::findFile(cascadeName)))
{
cerr << "错误:无法加载分类器级联" << endl;
help(argv);
return -1;
}
if( inputName.empty() || (isdigit(inputName[0]) && inputName.size() == 1) )
{
int camera = inputName.empty() ? 0 : inputName[0] - '0';
if(!capture.open(camera))
{
cout << "从摄像头 #" << camera << " 捕获失败" << endl;
return 1;
}
}
else if (!inputName.empty())
{
image = imread(samples::findFileOrKeep(inputName), IMREAD_COLOR);
if (image.empty())
{
if (!capture.open(samples::findFileOrKeep(inputName)))
{
cout << "无法读取 " << inputName << endl;
return 1;
}
}
}
else
{
image = imread(samples::findFile("lena.jpg"), IMREAD_COLOR);
if (image.empty())
{
cout << "无法读取 lena.jpg" << endl;
return 1;
}
}
if( capture.isOpened() )
{
cout << "视频捕获已启动 ..." << endl;
for(;;)
{
capture >> frame;
if( frame.empty() )
break;
Mat frame1 = frame.clone();
detectAndDraw( frame1, cascade, nestedCascade, scale, tryflip );
char c = (char)waitKey(10);
if( c == 27 || c == 'q' || c == 'Q' )
break;
}
}
else
{
cout << "正在检测 " << inputName << " 中的面部。" << endl;
if( !image.empty() )
{
detectAndDraw( image, cascade, nestedCascade, scale, tryflip );
waitKey(0);
}
else if( !inputName.empty() )
{
/* 假定它是一个文本文件,包含
要处理的图像文件名列表 - 每行一个 */
FILE* f = fopen( inputName.c_str(), "rt" );
if( f )
{
char buf[1000+1];
while( fgets( buf, 1000, f ) )
{
int len = (int)strlen(buf);
while( len > 0 && isspace(buf[len-1]) )
len--;
buf[len] = '\0';
cout << "文件 " << buf << endl;
image = imread( buf, IMREAD_COLOR );
if( !image.empty() )
{
detectAndDraw( image, cascade, nestedCascade, scale, tryflip );
char c = (char)waitKey(0);
if( c == 27 || c == 'q' || c == 'Q' )
break;
}
else
{
cerr << "糟糕,无法读取图像 " << buf << endl;
}
}
fclose(f);
}
}
}
return 0;
}
void detectAndDraw( Mat& img, CascadeClassifier& cascade,
CascadeClassifier& nestedCascade,
double scale, bool tryflip )
{
double t = 0;
vector<Rect> faces, faces2;
const static Scalar colors[] =
{
Scalar(255,0,0),
Scalar(255,128,0),
Scalar(255,255,0),
Scalar(0,255,0),
Scalar(0,128,255),
Scalar(0,255,255),
Scalar(0,0,255),
Scalar(255,0,255)
};
Mat gray, smallImg;
cvtColor( img, gray, COLOR_BGR2GRAY );
double fx = 1 / scale;
resize( gray, smallImg, Size(), fx, fx, INTER_LINEAR_EXACT );
equalizeHist( smallImg, smallImg );
t = (double)getTickCount();
cascade.detectMultiScale( smallImg, faces,
1.1, 2, 0
//|CASCADE_FIND_BIGGEST_OBJECT
//|CASCADE_DO_ROUGH_SEARCH
|CASCADE_SCALE_IMAGE,
Size(30, 30) );
if( tryflip )
{
flip(smallImg, smallImg, 1);
cascade.detectMultiScale( smallImg, faces2,
1.1, 2, 0
//|CASCADE_FIND_BIGGEST_OBJECT
//|CASCADE_DO_ROUGH_SEARCH
|CASCADE_SCALE_IMAGE,
Size(30, 30) );
for( vector<Rect>::const_iterator r = faces2.begin(); r != faces2.end(); ++r )
{
faces.push_back(Rect(smallImg.cols - r->x - r->width, r->y, r->width, r->height));
}
}
t = (double)getTickCount() - t;
printf( "检测时间 = %g 毫秒\n", t*1000/getTickFrequency());
for ( size_t i = 0; i < faces.size(); i++ )
{
Rect r = faces[i];
Mat smallImgROI;
vector<Rect> nestedObjects;
Point center;
Scalar color = colors[i%8];
int radius;
double aspect_ratio = (double)r.width/r.height;
if( 0.75 < aspect_ratio && aspect_ratio < 1.3 )
{
center.x = cvRound((r.x + r.width*0.5)*scale);
center.y = cvRound((r.y + r.height*0.5)*scale);
radius = cvRound((r.width + r.height)*0.25*scale);
circle( img, center, radius, color, 3, 8, 0 );
}
else
rectangle( img, Point(cvRound(r.x*scale), cvRound(r.y*scale)),
Point(cvRound((r.x + r.width-1)*scale), cvRound((r.y + r.height-1)*scale)),
color, 3, 8, 0);
if( nestedCascade.empty() )
continue;
smallImgROI = smallImg( r );
nestedCascade.detectMultiScale( smallImgROI, nestedObjects,
1.1, 2, 0
//|CASCADE_FIND_BIGGEST_OBJECT
//|CASCADE_DO_ROUGH_SEARCH
//|CASCADE_DO_CANNY_PRUNING
|CASCADE_SCALE_IMAGE,
Size(30, 30) );
for ( size_t j = 0; j < nestedObjects.size(); j++ )
{
Rect nr = nestedObjects[j];
center.x = cvRound((r.x + nr.x + nr.width*0.5)*scale);
center.y = cvRound((r.y + nr.y + nr.height*0.5)*scale);
radius = cvRound((nr.width + nr.height)*0.25*scale);
circle( img, center, radius, color, 3, 8, 0 );
}
}
imshow( "结果", img );
}
用于对象检测的级联分类器类。
Definition objdetect.hpp:258
bool empty() const
检查分类器是否已加载。
bool load(const String &filename)
从文件加载分类器。
void detectMultiScale(InputArray image, std::vector< Rect > &objects, double scaleFactor=1.1, int minNeighbors=3, int flags=0, Size minSize=Size(), Size maxSize=Size())
在输入图像中检测不同大小的对象。检测到的对象作为列表返回...
专为命令行解析设计。
定义 utility.hpp:890
n 维密集数组类
定义于 mat.hpp:840
CV_NODISCARD_STD Mat clone() const
创建数组及其底层数据的完整副本。
int cols
定义 mat.hpp:2204
bool empty() const
如果数组没有元素,则返回 true。
用于 2D 矩形的模板类。
定义 types.hpp:444
_Tp x
左上角x坐标
定义 types.hpp:487
_Tp y
左上角y坐标
定义 types.hpp:488
_Tp width (宽度)
矩形的宽度
定义 types.hpp:489
_Tp height (高度)
矩形的高度
定义 types.hpp:490
用于指定图像或矩形大小的模板类。
定义 types.hpp:335
从视频文件、图像序列或摄像头捕获视频的类。
定义 videoio.hpp:786
virtual bool open(const String &filename, int apiPreference=CAP_ANY)
打开视频文件、捕获设备或 IP 视频流进行视频捕获。
virtual bool isOpened() const
如果视频捕获已初始化,则返回 true。
#define CV_VERSION
Definition version.hpp:19
void flip(InputArray src, OutputArray dst, int flipCode)
沿垂直轴、水平轴或双轴翻转二维数组。
int cvRound(double value)
将浮点数舍入为最近的整数。
定义 fast_math.hpp:200
double getTickFrequency()
返回每秒的滴答数。
int64 getTickCount()
返回滴答数。
@ circle
定义 gr_skig.hpp:62
void imshow(const String &winname, InputArray mat)
在指定窗口中显示图像。
int waitKey(int delay=0)
等待按键操作。
Mat imread(const String &filename, int flags=IMREAD_COLOR_BGR)
从文件加载图像。
void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0, AlgorithmHint hint=cv::ALGO_HINT_DEFAULT)
将图像从一种颜色空间转换为另一种。
void rectangle(InputOutputArray img, Point pt1, Point pt2, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
绘制一个简单的、粗线条的或填充的正矩形。
void equalizeHist(InputArray src, OutputArray dst)
对灰度图像进行直方图均衡化。
void resize(InputArray src, OutputArray dst, Size dsize, double fx=0, double fy=0, int interpolation=INTER_LINEAR)
调整图像大小。
int main(int argc, char *argv[])
定义 highgui_qt.cpp:3
void scale(cv::Mat &mat, const cv::Mat &range, const T min, const T max)
Definition quality_utils.hpp:90
定义 core.hpp:107
STL 命名空间。