Repository navigation
Expand file tree
/
Copy pathObjectDetector.cpp
More file actions
92 lines (84 loc) · 2.38 KB
/
Copy pathObjectDetector.cpp
File metadata and controls
92 lines (84 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
* ObjectDetector.cpp
*
* Created on: Sep 5, 2014
* Author: davy
*/
#include "ObjectDetector.h"
void ObjectDetector::detectBiggestObject(const Mat &img,Rect &object, int DETECTION_WIDTH)
{
// Shrink the image, to run faster
Mat smallImg;
float scale = img.cols / (float) DETECTION_WIDTH;
if (img.cols > DETECTION_WIDTH) {
// Shrink image while keeping same aspect ratio.
int scaledHeight = cvRound(img.rows/scale);
resize(img, smallImg, Size(DETECTION_WIDTH, scaledHeight));
}
else {
// img already small
smallImg = img;
}
Mat gray;
if(smallImg.channels() == 3){
cvtColor(smallImg, gray, CV_BGR2GRAY);
}
else if (img.channels() == 4) {
cvtColor(smallImg, gray, CV_BGRA2GRAY);
}
else {
// Access grayscale input directly
gray = smallImg;
}
Mat equalizedImg;
equalizeHist(gray, equalizedImg);
//Detection
int flags = CASCADE_FIND_BIGGEST_OBJECT; //Search biggest object
Size minFeatureSize(80,80); //Smallest object Size
float searchScaleFactor = 1.1f;
int minNeighbors = 1; //Reliability vs many objects
vector<Rect> objects;
objectDetector.detectMultiScale(equalizedImg, objects,searchScaleFactor,
minNeighbors,flags, minFeatureSize);
if(objects.size() > 0) //There is an object detected
{
object = objects[0];
// Enlarge if the image was shrunk before detection.
if (img.cols > DETECTION_WIDTH)
{
//for (int i = 0; i < (int)objects.size(); i++ )
//{
object.x = cvRound(object.x * scale);
object.y = cvRound(object.y * scale);
object.width = cvRound(object.width * scale);
object.height = cvRound(object.height * scale);
//}
}
// Make sure the object is completely within the image, in case it was on a border.
//for (int i = 0; i < (int)objects.size(); i++ )
//{
if (object.x < 0)
object.x = 0;
if (object.y < 0)
object.y = 0;
if (object.x + object.width > img.cols)
object.x = img.cols - object.width;
if (object.y + object.height > img.rows)
object.y = img.rows - object.height;
//}
}
}
void ObjectDetector::initDetector(const char* cascadeFilename)
{
try{
objectDetector.load(cascadeFilename);
}
catch (cv::Exception e){}
if (objectDetector.empty())
{
cerr << "ERROR: Couldn't load Face Detector(";
cerr << cascadeFilename << ")!" << endl;
exit(1);
}
this->DETECTION_WIDTH = DETECTION_WIDTH;
}