我有一个 OpenCV 程序,它使用多个 Haar 分类器在单个窗口中检测多个对象。检测到第一个对象并按照应有的方式绘制椭圆但是当检测到两个辅助对象时,不会为检测到的每个实例绘制圆(检测到对象时我将输出到控制台)。
我正在指定三个分类器,如下所示:
String cascade_name = "frontalface.xml";
String nestcascade_name = "body.xml";
String nested_cascade_name_two = "HandCascade.xml";
然后我使用以下方法加载分类器:
cascade_one.load( cascade_name )
cascade_two.load( nested_cascade_name )
cascade_three.load( nested_cascade_name_two )
然后我为三个对象创建三个向量:
std::vector<Rect> firstObject;
std::vector<Rect> secondObject;
std::vector<Rect> thirdObject;
然后我使用以下代码检测并在屏幕上绘制对象:
cascade_one.detectMultiScale( frame_gray, firstObject, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( size_t i = 0; i < firstObject.size(); i++ ) {
Point center( firstObject[i].x + firstObject[i].width*0.5, firstObject[i].y + firstObject[i].height*0.5 );
ellipse( frame, center, Size( firstObject[i].width*0.5, firstObject[i].height*0.5), 0, 0, 360, Scalar( 0, 255, 0 ), 4, 8, 0 ); //GREEN
std::cout << " " << cascade_name << " " << timeFound() << endl;
}
更改每个对象cascade_one
firstObject
的cascade_name
相关名称。为什么第一个对象工作正常,但第二个和第三个对象虽然没有在屏幕上全部绘制,却输出了多个检测?
编辑:
完整的检测和绘制代码:
void detectAndDisplay( Mat frame ) {
std::vector<Rect> firstObject;
std::vector<Rect> secondObject;
std::vector<Rect> thirdObject;
Mat frame_gray;
cvtColor( frame, frame_gray, CV_BGR2GRAY );
equalizeHist( frame_gray, frame_gray );
//-- Detect object
cascade_one.detectMultiScale( frame_gray, firstObject, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( size_t i = 0; i < firstObject.size(); i++ ) {
Point center( firstObject[i].x + firstObject[i].width*0.5, firstObject[i].y + firstObject[i].height*0.5 );
ellipse( frame, center, Size( firstObject[i].width*0.5, firstObject[i].height*0.5), 0, 0, 360, Scalar( 0, 255, 0 ), 4, 8, 0 ); //GREEN
std::cout << " " << cascade_name << " " << timeFound() << endl;
}
//-- detect second object
cascade_two.detectMultiScale( frame_gray, secondObject, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( size_t k = 0; k < secondObject.size(); k++ ) {
Point center( secondObject[k].x + secondObject[k].x + secondObject[k].width*0.5, secondObject[k].y + secondObject[k].y + secondObject[k].height*0.5 );
int radius = cvRound( (secondObject[k].width + secondObject[k].height)*0.25 );
circle( frame, center, radius, Scalar( 255, 0, 0 ), 4, 8, 0 ); //BLUE
std::cout << " " << nested_cascade_name << " " << timeFound() << endl;
}
//-- detect third object
cascade_three.detectMultiScale( frame_gray, thirdObject, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( size_t j = 0; j < thirdObject.size(); j++ ) {
Point center( thirdObject[j].x + thirdObject[j].x + thirdObject[j].width*0.5, thirdObject[j].y + thirdObject[j].y + thirdObject[j].height*0.5 );
int radius = cvRound( (thirdObject[j].width + thirdObject[j].height)*0.25 );
circle( frame, center, radius, Scalar( 0, 0, 255 ), 4, 8, 0 ); //RED
std::cout << " " << nested_cascade_name_two << " " << timeFound() << endl;
}
imshow( window_name, frame );
}