Vous êtes sur la page 1sur 30

World of OpenCV, AI, Computer Vision and Robotics Examples and Tutorials

Search for:

 Home
 Raspberry Pi
 Tutorials Bundle
 Guide to ESP Arduino
 OpenCV (c++)
 OpenCV (python)
 SVM + HOG
 DEEP Learning VM
 About Me
 Contact

1.
2. (Best and Easy) Support Vector Machines(SVM) + HOG Tutorial | OpenCV 3.0, 3.1, 3.2, 3.3 | Windows 10 | Visual
Studio 2015 | x64 | Train & Test
3. (Best and Easy) Support Vector Machines(SVM) + HOG Tutorial | OpenCV 3.0, 3.1, 3.2, 3.3 | Windows 10 | Visual
Studio 2015 | x64 | Train & Test

(Best and Easy) Support Vector Machines(SVM) +


HOG Tutorial | OpenCV 3.0, 3.1, 3.2, 3.3 |
Windows 10 | Visual Studio 2015 | x64 | Train &
Test
Editor November 24, 2017 C++ OpenCV Tutorials , Support Vector Machines, Trending Posts 3 Comments

Hello Friends,

Have you ever wondered how can you create your own OpenCV 3 Support Vector Machines(SVM) + HOG
Classifier? Did you want to create your own classifier that actually works? Are you tried of searching google
for a good SVM tutorial but all you find it bunch of example SVM Tutorials that does nothing but show a test
image with useless circles?
If the answer is Yes! , you have come to the right place my friend.
I have myself struggled a lot to get this working all because there wasn’t a good tutorial anywhere that existed
which would teach you the SVM.
In this tutorial, we’ll create a simple Car Detector using SVM aka Support Vector Machines.
So, before we get started, let’s look at the pre-requisites.

1) Visual Studio 2015


2) Windows 10 x64 (works best)
3) OpenCV 3.0, 3.1, 3.2, 3.3 and above
4) Patience !!

If you are someone who doesn’t really bother what’s going on behind the scene and would want to straight out
implement this goddamn classifier, then without further due, let’s look at the code. (Although, i would prefer
that you understand what’s what before actually using it, but I know you always don’t have that

options !!!)

Special Note: A lot of things have changed between OpenCV 2.x and OpenCV 3.x builds with respect to
SVM. I mean if you are trying to port the code or maybe using the existing classifier that you created in
OpenCV 2.x in OpenCV 3.x, man you better off start fresh because things have changed like hell.

Step by Step for Training Phase:


1) Create a new ’empty’ project in Visual Studio 2015
2) Link the OpenCV Includes and Libs with the project (Follow this link on how to install OpenCV 3.3 with
Visual Studio and run a test Solution)
3) For Training, Create 3 files namely:
a) Train.cpp
b) Datamanager.cpp
c) Datamanager.h
4) Name your classifier file under “svm->save(“firetrain.yml”);” to your desired filename
5) Create a folder called “Positive” inside the project and add all the positive images to it. (Size 64×64)
6) Create a folder called “Negative” inside the project and add all the Negative images to it. (Size 64×64)
7) (Optional) Use svm->trainAuto(td); instead of svm->train(td) to set value of C and gamma, but it takes a lot
of time

Note: Shortly, after this post, i’ll create a crop_image software to assist you with the cropping of images.

Step by Step for Detection Phase:


1) Create a new ’empty’ project in Visual Studio 2015
2) Link the OpenCV Includes and Libs with the project (Follow this link on how to install OpenCV 3.3 with
Visual Studio and run a test Solution)
3) For Detection, Create 1 file called “DetectCode.cpp” by excluding the above 3 training files and also
referencing the classifier file in “#define TRAINED_SVM “firetrain.yml” that you created in training phase.
Note: There are hog parameters that you need to tune accordingly. I have plans to create a HOG based
UI software, so that you can easily get all those parameters from your referenced image. Stay tuned for
updates for it.

Algorithm pipeline(Training svm):


– > From the image dataset that you have created, randomly separate it into training and test set(80%, 20%
split)
– > Set the hog windowSize(64×64) and Compute the HOG features for the training image set containing
vehicles and non-vehicles.
– > Train a SVM using these HOG features. (Use linear or RBF SVM)
– > Test the trained SVM on the separate test imageset and evaluate the results and performance.
– > For the real world test, run a sliding window and use the SVM from above to predict vehicle/non-vehicle.

Algorithm pipeline(Detectting car in video):


– > Extract individual frame of the video frames.
– > Convert each captured frame into grayscale image.
– > Discard the upper half containing the sky part.
– > Choose a sliding window size, and resize to the trained size; Use SVM to predict
– > Filter the detect points for false positive(use template matching only for the subsection of detected)

Codes :

#Train.cpp

1 //train.cpp
2 #include <opencv2/opencv.hpp>
3 //#include <opencv2/ml.hpp>
4
5 #include <iostream>
6 #include <string>
7 //#include "util/imageutils.h"
8 #include "DataSetManager.h"
9
10
11
12 using namespace std;
13 using namespace cv;
14 using namespace cv::ml;
15
16
17
18 HOGDescriptor hog(
19 Size(64,64), //winSize
20 Size(8,8), //blocksize
21 Size(8,8), //blockStride,
22 Size(8,8), //cellSize,
23 9, //nbins,
24 1, //derivAper,
25 -1, //winSigma,
26 0, //histogramNormType,
27 0.2, //L2HysThresh,
28 0,//gammal correction,
29 64,//nlevels=64
30 1);
31
32
33
34
35 void getSVMParams(SVM *svm)
36 {
37 cout << "Kernel type : " << svm->getKernelType() << endl;
38 cout << "Type : " << svm->getType() << endl;
39 cout << "C : " << svm->getC() << endl;
40 cout << "Degree : " << svm->getDegree() << endl;
41 cout << "Nu : " << svm->getNu() << endl;
42 cout << "Gamma : " << svm->getGamma() << endl;
43 }
44
45 void SVMtrain(Mat &trainMat, vector<int> &trainLabels, Mat &testResponse, Mat &testMat)
46 Ptr<SVM> svm = SVM::create();
47 svm->setGamma(0.50625);
48 svm->setC(100);
49 svm->setKernel(SVM::RBF);
50 svm->setType(SVM::C_SVC);
51 Ptr<TrainData> td = TrainData::create(trainMat, ROW_SAMPLE, trainLabels);
52 svm->train(td);
53 //svm->trainAuto(td);
54 svm->save("firetrain.yml");
55 svm->predict(testMat, testResponse);
56 getSVMParams(svm);
57
58 /*
59 To acheive 100% rate.
60 Descriptor Size : 576
61 Kernel type : 2
62 Type : 100
63 C : 2.5
64 Degree : 0
65 Nu : 0
66 Gamma : 0.03375
67 the accuracy is :100
68
69 */
70
71 }
72
73 void SVMevaluate(Mat &testResponse, float &count, float &accuracy, vector<int> &testLab
74
75 for (int i = 0; i<testResponse.rows; i++)
76 {
77 //cout << testResponse.at<float>(i,0) << " " << testLabels[i] << endl;
78 if (testResponse.at<float>(i, 0) == testLabels[i]) {
79 count = count + 1;
80 }
81 }
82 accuracy = (count / testResponse.rows) * 100;
83 }
84 void computeHOG(vector<Mat> &inputCells, vector<vector<float> > &outputHOG) {
85
86 for (int y = 0; y<inputCells.size(); y++) {
87 vector<float> descriptors;
88 hog.compute(inputCells[y], descriptors);
89 outputHOG.push_back(descriptors);
90 }
91 }
92 void ConvertVectortoMatrix(vector<vector<float> > &ipHOG, Mat & opMat)
93 {
94
95 int descriptor_size = ipHOG[0].size();
96 for (int i = 0; i<ipHOG.size(); i++) {
97 for (int j = 0; j<descriptor_size; j++) {
98 opMat.at<float>(i, j) = ipHOG[i][j];
99 }
10 }
0 }
10
1 int main(int argc, char ** argv)
10 {
2
10 /**************** user code starts *******************/
3 cout << " User code starts" << endl;
10 DataSetManager dm;
4 dm.addData("Positive", 1);// positive train data
10 dm.addData("Negative", -1);// negative train data
5 //dm.addDa
10 // can als
6 n"
10 //dm.addDa
7 cout << "Total data length : " << dm.getTotalDataNum() << endl;
10 dm.distribute();
8 dm.display();
10 /***********load all the dataset into vector of Mat*********/
9 vector<Mat> trainCells;
11 vector<Mat> testCells;
0 vector<int> trainLabels;
11 vector<int> testLabels;
1 for (int i = 0; i<dm.getTotalTrainDataNum(); i++) {
11 string imageName = dm.TrainData[i].filename;
2 Mat img = imread(imageName, CV_LOAD_IMAGE_GRAYSCALE);
11 trainCells.push_back(img);
3 trainLabels.push_back(dm.TrainData[i].label);
11 }
4 for (int i = 0; i<dm.getTotalTestDataNum(); i++) {
11 string imageName = dm.TestData[i].filename;
5 Mat img = imread(imageName, CV_LOAD_IMAGE_GRAYSCALE);
11 testCells.push_back(img);
6 testLabels.push_back(dm.TestData[i].label);
11 }
7 //loadTrainTestLabel(pathName,trainCells,testCells,trainLabels,testLabels);
11 /***********Computer HOG descriptor for all the training and testcells ********
8 std::vector<std::vector<float> > trainHOG;
11 std::vector<std::vector<float> > testHOG;
9
12 //compute_hog(trainCells, gradient_lst);
0 computeHOG(trainCells, trainHOG);
12 computeHOG(testCells, testHOG);
1
12 int descriptor_size = trainHOG[0].size();
2 cout << "Descriptor Size : " << descriptor_size << endl;
12 /******** HOG descriptor ends ****************************/
3
12 /********Prepeare trainData and test data and call SVM ML algorithm*********/
4 Mat trainMat(trainHOG.size(), descriptor_size, CV_32FC1);
12 Mat testMat(testHOG.size(), descriptor_size, CV_32FC1);
5 ConvertVectortoMatrix(trainHOG, trainMat);
12 ConvertVectortoMatrix(testHOG, testMat);
6
12 Mat testResponse;
7 SVMtrain(trainMat, trainLabels, testResponse, testMat);
12
8 float count = 0;
12 float accuracy = 0;
9 SVMevaluate(testResponse, count, accuracy, testLabels);
13
0 cout << "the accuracy is :" << accuracy << endl;
13
1 /**************** user code ends *******************/
13
2 //waitKey(0);
13 char ch;
3 cin >> ch;
13 return 0;
4
13 }
5
13
6
13
7
13
8
13
9
14
0
14
1
14
2
14
3
14
4
14
5
14
6
14
7
14
8
14
9
15
0
15
1
15
2
15
3
15
4
15
5
15
6
15
7
15
8
15
9
16
0
16
1
16
2
16
3
16
4
16
5
16
6
16
7
16
8
16
9

#DataSetManager.cpp

1 //DataSetManager.cpp
2 #include <opencv2/opencv.hpp>
3 #include <iostream>
4 #include <string>
5 #include "DataSetManager.h"
6 #include <algorithm>
7
8 using namespace cv;
9 using std::cout;
10 using std::endl;
11 using std::string;
12
13 #define EN_DEBUG
14
15 //constructor
16 DataSetManager::DataSetManager() :testDataPercent(20), validationDataPercent(0), totalD
17 (0) {
18 // default parameter initialization here
19 }
20 // setter and getter methods
21
22 void DataSetManager::setTestDataPercent(float num) { testDataPercent = num; }
23 void DataSetManager::setValidationDataPercent(float num) { validationDataPercent = num;
24 int DataSetManager::getTotalDataNum() { return totalDataNum; }
25 int DataSetManager::getTotalTrainDataNum() { return totalTrainDataNum; }
26 int DataSetManager::getTotalTestDataNum() { return totalTestDataNum; }
27
28 //main functions
29 void DataSetManager::addData(std::string folderName, int classlabel) {
30 // notice here that we are using the Opencv's embedded "String" class
31 std::vector<cv::String> filenames;
32 cv::String folder = folderName.c_str();// converting from std::string->cv::Stri
33 cv::glob(folder, filenames);
34 // for each of these fileNames append them into the DataSet structure with labe
35 for (size_t i = 0; i<filenames.size(); i++) {
36 DataSet tempDataset;
37 tempDataset.filename = static_cast<std::string>(filenames[i]);
38 tempDataset.label = classlabel;
39 dataList.push_back(tempDataset);
40 }
41 totalDataNum = totalDataNum + filenames.size();
42 }
43
44 // the distribute functions distributes the whole data into training data and test data
45 void DataSetManager::distribute() {
46 int n_test_valid = static_cast<int> (
47 (validationDataPercent*totalDataNum / 100) + (testDataPercent*totalData
48 //cout<<" n_test_valid == "<< n_test_valid<<endl;
49 int counter = 0;
50 std::vector<int> rndIndex;
51 std::vector<int>::iterator it;
52 DataSet tempDataset;
53 while (counter<n_test_valid) {
54 // random number between [0-totalDataNum-1]
55 int num = rand() % totalDataNum;
56 it = std::find(rndIndex.begin(), rndIndex.end(), num);
57 if (it != rndIndex.end())
58 continue;//skip the rest of the loop if this num is already pres
59 //we are here only if the 'num' is unique
60 rndIndex.push_back(num);
61 //cout<<" random number == "<< num<<endl;
62 tempDataset.filename = static_cast<std::string>(dataList[num].filename)
63 tempDataset.label = dataList[num].label;
64 TestData.push_back(tempDataset);
65 counter++;
66 }
67 std::sort(rndIndex.begin(), rndIndex.end());//sort in ascending order
68 #ifdef EN_DEBUG
69 cout << "sortedIndexes: " << endl;
70 for (std::vector<int>::iterator it = rndIndex.begin(); it != rndIndex.end(); ++
71 cout << " " << *it << endl;
72 cout << endl;
73 #endif
74
75 //cout<<" now fill the TrainData; only exclude the testData"<<endl;
76
77 int curIdx = 0;
78 int current = rndIndex[curIdx];
79 //cout<<"rndIndex.size()= "<<rndIndex.size()<<endl;
80 for (int i = 0; i<dataList.size(); i++) {
81 //cout<<" current == "<< current<<" i = "<<i<<" curIndx= "<< curIdx;
82 if (i != current) {
83 //cout<<" inside Train";
84 tempDataset.filename = static_cast<std::string>(dataList[i].file
85 tempDataset.label = dataList[i].label;
86 TrainData.push_back(tempDataset);
87 }
88 else if ((current == i) && (curIdx<rndIndex.size() - 1)) {
89 //cout<<" inside Test";
90 current = rndIndex[++curIdx];
91 }
92 }
93
94 totalTrainDataNum = TrainData.size();
95 totalTestDataNum = TestData.size();
96 }
97 void DataSetManager::display() {
98
99 // display Data
10 cout << "Training data length: " << getTotalTrainDataNum() << endl;
0 #ifdef EN_DEBUG
10 for (int i = 0; i<getTotalTrainDataNum(); i++) {
1 cout << " filename: " << TrainData[i].filename;
10 cout << " \tlabels: " << TrainData[i].label << endl;
2 }
10 #endif
3 cout << "Test data length: " << getTotalTestDataNum() << endl;
10 #ifdef EN_DEBUG
4 for (int i = 0; i<getTotalTestDataNum(); i++) {
10 cout << " filename: " << TestData[i].filename;
5 cout << " \tlabels: " << TestData[i].label << endl;
10 }
6 #endif
10
7 }
10
8
10
9
11
0
11
1
11
2
11
3
11
4

#DataSetManager.h

#ifndef _DATASETMANAGER_H
1
#define _DATASETMANAGER_H
2
3
#include <iostream>
4
5
struct DataSet {
6
std::string filename;
7
float label;
8
};
9
1
class DataSetManager
0
{
1
private:
1
// user defined data member
1
float testDataPercent;
2
float validationDataPercent;
1
3
// derrived or internally calculated
1
int totalDataNum;
4
int totalTrainDataNum;
1
int totalTestDataNum;
5
int totalValidationDataNum;
1
6
public:
1
//constructor
7
DataSetManager();
1
8
// setter and getter methods
1
void setTestDataPercent(float num);
9
void setValidationDataPercent(float num);
2
0
int getTotalDataNum();
2
int getTotalTrainDataNum();
1
int getTotalTestDataNum();
2
int getTotalValidationDataNum();
2
2
// primary functions of the class
3
void addData(std::string folderName, int classlabel);
2
void read();
4
void display();// displays the read file names for debugging
2
void distribute();
5
// ideally these are private; need to update
2
std::vector<DataSet> dataList;
6
std::vector<DataSet> TrainData;
2 std::vector<DataSet> TestData;
7 std::vector<DataSet> ValidationData;
2 };
8
2 #endif
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9

DetectCode.cpp

1 //detectcar.cpp
2 #include <opencv2/opencv.hpp>
3 #include <iostream>
4 #include <vector>
5 #include <string>
6 #include <fstream>
7 #include <ctime>
8
9
1 #include <io.h>
0 #include <memory>
1
1
1 #define WINDOW_NAME "WINDOW"
2
1 #define TRAFFIC_VIDEO_FILE "7.avi"
3 #define TRAINED_SVM "firetrain.yml"
1 #define IMAGE_SIZE Size(40,40)
4 #define save_video true
1 #define OUT_Video_File "march323230_project_video.avi"
5
1 using namespace cv;
6 using namespace cv::ml;
1 using namespace std;
7
1 bool file_exists(const string &file);
8
1 void draw_locations(Mat & img, const vector< Rect > & locations, const Scalar & color);
9
2 void readImage(string imgname, Mat & im);
0 //void test_image(Mat & img, const Size & size);
2 void test_video(const Size & size);
1 bool checkIfpatchIsVehicle(Mat & img2check);
2
2 void printHOGParams(HOGDescriptor &hog)
2 {
3 cout << "HOG descriptor size is " << hog.getDescriptorSize() << endl;
2 cout << "hog.windowSize: " << hog.winSize << endl;
4 cout << " cellsize " << hog.cellSize << endl;
2 cout << " hog.nbins " << hog.nbins << endl;
5 cout << " blockSize " << hog.blockSize << endl;
2 cout << " blockStride " << hog.blockStride << endl;
6 cout << " hog.nlevels " << hog.nlevels << endl;
2 cout << " hog.winSigma " << hog.winSigma << endl;
7 cout << " hog.free_coef " << hog.free_coef << endl;
2 cout << " hog.DEFAULT_NLEVELS " << hog.DEFAULT_NLEVELS << endl;
8
2 }
9
3
0 int main(int argc, char** argv)
3 {
1
3
2 test_video(IMAGE_SIZE);
3 return 0;
3 }
3 void readImage(string imgname, Mat & im) {
4
3 im = imread("54.jpg", IMREAD_COLOR);
5 if (im.empty())
{
3 cout << " Invalid image read, imgname =argv[1] = " << imgname << endl;
6 CV_Assert(false);
3 }
7 //cout<<"****** successfully image read, imgname = "<<imgname<<endl;
3 }
8
3 bool file_exists(const string &file)
9 {
4 return _access(file.c_str(), 0) == 0;
0 }
4
1
4
2
4 void get_svm_detector(const Ptr<SVM>& svm, vector< float > & hog_detector)
3 {
4 // get the support vectors
4 Mat sv = svm->getSupportVectors();
4 const int sv_total = sv.rows;
5 // get the decision function
4 Mat alpha, svidx;
6 double rho = svm->getDecisionFunction(0, alpha, svidx);
4 cout << "alpha = " << alpha << endl;
7 //CV_Assert(alpha.total() == 1 && svidx.total() == 1 && sv_total == 1);
4 //CV_Assert((alpha.type() == CV_64F && alpha.at<double>(0) == 1.) ||
8 //(alpha.type() == CV_32F && alpha.at<float>(0) == 1.f));
4 //CV_Assert(sv.type() == CV_32F);
9 hog_detector.clear();
5
0 hog_detector.resize(sv.cols + 1);
5 memcpy(&hog_detector[0], sv.ptr(), sv.cols * sizeof(hog_detector[0]));
1 hog_detector[sv.cols] = (float)-rho;
5 }
2
5 void draw_locations(Mat & img, const vector< Rect > & locations, const Scalar & color)
3 {
5 if (!locations.empty())
4 {
5 vector< Rect >::const_iterator loc = locations.begin();
5 vector< Rect >::const_iterator end = locations.end();
5 for (; loc != end; ++loc)
6 {
5 rectangle(img, *loc, color, 2);
7 }
5 }
8 }
5
9 void test_video(const Size & size)
6 {
0 char key = 27;
6 Mat img, draw;
1 Ptr<SVM> svm;
6 HOGDescriptor hog;
2 hog.winSize = size;
6 vector< Rect > locations;
3 vector< Rect > found_filtered;
6
4 // Load the trained SVM.
6 svm = StatModel::load<SVM>(TRAINED_SVM);
5 // Set the trained svm to my_hog
6 vector< float > hog_detector;
6 get_svm_detector(svm, hog_detector);
6 hog.setSVMDetector(hog_detector);
7 printHOGParams(hog);
6
8 VideoCapture video;
6 // Open the video file.
9 video.open(TRAFFIC_VIDEO_FILE);
7 if (!video.isOpened())
0 {
7 cerr << "Unable to open the device" << endl;
1 exit(-1);
7 }
2 // Get the frame rate
7 double rate = video.get(CV_CAP_PROP_FPS);
3 cout << " Frame rate : " << rate << endl;
7 cout << " Input video codec :" << video.get(CV_CAP_PROP_FOURCC);
4 // initilaize the video writer object to write the video output
7 std::string outputFile(OUT_Video_File);
5 VideoWriter writer;
7 int codec = static_cast<int>(video.get(CV_CAP_PROP_FOURCC));
6 //int codec = CV_FOURCC('M', 'J', 'P', 'G');
7 bool isWriterInitialized = false;
7
7 int num_of_vehicles = 0;
8 bool end_of_process = false;
7 while (!end_of_process)
9 {
8 video >> img;
0 if (img.empty())
8 break;
1
8
2 draw = img.clone();
8 Mat cropped;
3 cv::resize(draw, cropped, Size(720, 560));
8
4 Mat temp, temp3;
8 cvtColor(cropped, temp, COLOR_BGR2GRAY);
5 /*Mat bgr[3]; //destination array
8 split(temp3,bgr);//split source
6 temp = bgr[0]+bgr[2];
8 */
7 if (isWriterInitialized) {
8 //execute only once
8 isWriterInitialized = true;
8 /*writer.open(outputFile,
9 capture.get(CV_CAP_PROP_FOURCC),
9 capture.get(CV_CAP_PROP_FPS),
0 Size(capture.get(CV_CAP_PROP_FRAME_WIDTH),capture.get(CV_CAP_PROP_
9 true);*/
1 writer.open(outputFile, codec, rate, cropped.size(), true);
9 }
2
9
3 locations.clear();
9 // Rect(x,y,w,h) w->width=cols;h->rows
4 // first remove the upper 50% from height Original Cropped =size(720,560
9 Mat roi = temp(Rect(0, temp.rows*0.5, temp.cols, temp.rows - temp.rows*0.
5 //size(roi) = size(720,280)
9 //cout<<"roi.size() = "<<roi.size()<<endl;
6 int y_offset = temp.rows*0.5;
9 //again crop the lower 10 % to remove the images near dashboard-> remove
7 roi = roi(Rect(0, 0, roi.cols, roi.rows - 100));
9 //cout<<"roi.size() = "<<roi.size()<<endl;
8 //no offset required as this is the lower row colums.
9
9 //hog.detectMultiScale(roi, locations);
1 //hog.detectMultiScale(roi, locations, 1, Size(50, 50), Size(32, 32), 1,
0
0
hog.detectMultiScale(roi, locations, 0.00, Size(4, 8), Size(0, 0), 1.05,
1
0
locations, 0.00, Size(8,8), Size(0,0), 1.05, 2);// less true negative(missed)
1
1
0
2
1
std::vector<Rect>::iterator it = locations.begin();
0
std::vector<Rect>::iterator itend = locations.end();
3
vector<Rect> actuallocations;
1
bool isVehicle = false;
0
for (; it != itend; it++)
4
{
1
Rect current = *it;
0
//cout<<" Rect current = "<< current<<endl;
5
//cout<<" roi size= "<<roi.size()<<endl;
1
Mat roi2Check = roi(Rect(current.x, current.y, current.width, curr
0
6
k size= "<<roi2Check.size()<<endl;
1
isVehicle = checkIfpatchIsVehicle(roi2Check);
0
if (isVehicle)
7
actuallocations.push_back(Rect(current.x, current.y + y_of
1
}
0
if (0 != actuallocations.size())
8
draw_locations(cropped, actuallocations, Scalar(0, 255, 0));
1
0
imshow(WINDOW_NAME, cropped);
9
1
1
0
1
1
if (save_video)
1
writer.write(cropped);
1
//wait infinite fro keypress
1
key = (char)waitKey(3);
2
if (27 == key)
end_of_process = true;
1 }
1 // Close the video file.
3 // Not required since called by destructor
1 writer.release();
1 video.release();
4}
1
1 bool checkIfpatchIsVehicle(Mat & img2check)
5{
1 //cout<<"******inside function checkIfPatchIsVehicle "<<endl;
1 bool isVehicle = false;
6 //util::imdisp(img2check,"im2check");
1 vector<string> templateList;
1 templateList.push_back("temp1.png"); templateList.push_back("temp2.png");
7 templateList.push_back("temp3.png"); templateList.push_back("temp4.png");
1 templateList.push_back("temp5.png"); templateList.push_back("temp6.png");
1 templateList.push_back("temp7.png");
8 //templateList.push_back("temp8.png");
1 //templateList.push_back("temp9.png");templateList.push_back("temp10.png");
1
9 Mat matchScore = Mat::zeros(7, 1, CV_32FC1);
1
2 for (int ii = 0; ii<templateList.size(); ii++) {
0 Mat result;
1
2 string imgname = templateList.at(ii);
1 Mat templ, img2check_copy;
1 readImage(imgname, templ);
2 cvtColor(templ, templ, COLOR_BGR2GRAY);
2 cv::resize(img2check, img2check, Size(50, 50));
1 cv::resize(templ, templ, Size(50, 50));
2 int result_cols = img2check.cols - templ.cols + 1;
3 int result_rows = img2check.rows - templ.rows + 1;
1
2 result.create(result_rows, result_cols, CV_32FC1);
4
1 Canny(img2check, img2check_copy, 50, 150);
2
5 //util::imdisp(img2check_copy,"canny");
1
2
6 /// Do the Matching and Normalize
1 matchTemplate(img2check_copy, templ, result, CV_TM_CCORR_NORMED);
2
7 /// Localizing the best match with minMaxLoc
1 double minVal; double maxVal; Point minLoc; Point maxLoc;
2 Point matchLoc;
8 minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, Mat());
1 matchScore.at<float>(ii, 0) = maxVal;
2 if (maxVal>0.15)
9 isVehicle = true;
1 }
3 //cout<<"MatchScore = "<<endl<<matchScore<<endl;
0 float total = sum(matchScore)[0];
cout << "sum(Matchscore) = " << cv::sum(matchScore)[0] << std::endl;
if (total>0.13*templateList.size())
1 isVehicle = true;
3 //waitKey();
1 return isVehicle;
1}
3
2
1
3
3
1
3
4
1
3
5
1
3
6
1
3
7
1
3
8
1
3
9
1
4
0
1
4
1
1
4
2
1
4
3
1
4
4
1
4
5
1
4
6
1
4
7
1
4
8
1
4
9
1
5
0
1
5
1
1
5
2
1
5
3
1
5
4
1
5
5
1
5
6
1
5
7
1
5
8
1
5
9
1
6
0
1
6
1
1
6
2
1
6
3
1
6
4
1
6
5
1
6
6
1
6
7
1
6
8
1
6
9
1
7
0
1
7
1
1
7
2
1
7
3
1
7
4
1
7
5
1
7
6
1
7
7
1
7
8
1
7
9
1
8
0
1
8
1
1
8
2
1
8
3
1
8
4
1
8
5
1
8
6
1
8
7
1
8
8
1
8
9
1
9
0
1
9
1
1
9
2
1
9
3
1
9
4
1
9
5
1
9
6
1
9
7
1
9
8
1
9
9
2
0
0
2
0
1
2
0
2
2
0
3
2
0
4
2
0
5
2
0
6
2
0
7
2
0
8
2
0
9
2
1
0
2
1
1
2
1
2
2
1
3
2
1
4
2
1
5
2
1
6
2
1
7
2
1
8
2
1
9
2
2
0
2
2
1
2
2
2
2
2
3
2
2
4
2
2
5
2
2
6
2
2
7
2
2
8
2
2
9
2
3
0
2
3
1
2
3
2
2
3
3
2
3
4
2
3
5
2
3
6
2
3
7
2
3
8
2
3
9
2
4
0
2
4
1
2
4
2
2
4
3
2
4
4
2
4
5
2
4
6
2
4
7
2
4
8
2
4
9
2
5
0
2
5
1
2
5
2
2
5
3
2
5
4
2
5
5
2
5
6
2
5
7
2
5
8
2
5
9
2
6
0
2
6
1
2
6
2
2
6
3
2
6
4
2
6
5
2
6
6
2
6
7
2
6
8
2
6
9
2
7
0
2
7
1
2
7
2
2
7
3
2
7
4
2
7
5
2
7
6
2
7
7
2
7
8
2
7
9
2
8
0
2
8
1
2
8
2
2
8
3
2
8
4
2
8
5
2
8
6
2
8
7
2
8
8

Files for Download


Test Images containing Positive and Negative Dataset
1) testdatafolder

(Easy & Fast) Pre-Compiled OpenCV Libraries and Headers for 3.2 with Visual Studio
2015 x64 Windows 10 Support
Modern C++ libraries for your OpenCV toolbox
Artcile Views: 1,743

 20

3 thoughts on “(Best and Easy) Support Vector Machines(SVM)


+ HOG Tutorial | OpenCV 3.0, 3.1, 3.2, 3.3 | Windows 10 |
Visual Studio 2015 | x64 | Train & Test”

1. jiesen says:

December 21, 2017 at 10:17 pm

Hi, where is the Traffic video you used for testing? Detection of my test videos is very slow.

Reply

2. Yunus Dönmez says:

January 1, 2018 at 12:16 am

I am wondering.The validationDataPercent value is 0.Why is not 80.I couldn’t understand it.

Reply

1. Editor says:

January 9, 2018 at 12:25 am

you can configure that as per your need.


Reply

Leave a Reply
Your email address will not be published. Required fields are marked *

Comment

Name *

Email *

Website

Post Comment

Search for:

Most Viewed Posts

 (Step by Step) Install OpenCV 3.3 with Visual Studio 2015 on Windows 10 x64 (2017 DIY)(9,602)

Hey Friends, I am starting my own blog series on OpenCV Development Tutorials and this being my
first post. As many of ...

 Simple Hand/Finger Tracking & Gesture Recognition(4,342)

Once again, hello !! In this post, we are going to cover Hand Gesture Tracking. It's one of my favorite
and fun ...
 Install OpenCV 3.3 and Python(2.7 & 3.5) bindings on Ubuntu 16.04(3,727)

Hello, In this post, we are going to cover, how to install OpenCV 3.3 and Python 2.7 or 3.5 bindings
on latest ...

 (Easy & Fast) Pre-Compiled OpenCV Libraries and Headers for 3.2 with Visual Studio 2015 x64
Windows 10 Support(3,688)

Hello Friends, Following our last post on installing OpenCV 3.3 as per the below link, i am sure most
of you might ...

 (COMPLETE, BEST & EASIEST) ESP8266-01 | ESP8266-12E/F Configuration Guide with Arduino
Nano/Mega/UNO for IoT Projects (Includes all ESP Issues)(3,281)

Hello Friends, Have you been trying real-hard to get your good old ESP8266 -01 / 12 E / 12 F
working with ...

Categories

ANDROID OPENCVARDUINO C++ OPENCV TUTORIALS DEEP

LEARNINGGENERAL OPENCV DISCUSSIONSINSTALLATION


TUTORIALSPYTHON OPENCV TUTORIALSRASPBERRY
PISUPPORT VECTOR MACHINESTRENDING POSTS

Recent Posts

 (Easy & Fast) Pre-Compiled OpenCV Libraries and Headers for 3.2 with Visual Studio 2015 x64
Windows 10 Support
 (Best and Easy) Support Vector Machines(SVM) + HOG Tutorial | OpenCV 3.0, 3.1, 3.2, 3.3 |
Windows 10 | Visual Studio 2015 | x64 | Train & Test
 OpenCV 3.3.1 vs 3.3.0 Changes (Release Notes)
 Turn your Raspberry Pi into old school retro gaming console using RetroPie (Windows & MAC)
 OpenCV Real-time Graph Plot using Matplotlib or Python-Drawnow

Welcome to OpenCV World !! Come as a


Guest, stay as a Family
Recent Posts

 (Easy & Fast) Pre-Compiled OpenCV Libraries and Headers for 3.2 with Visual Studio 2015 x64
Windows 10 Support November 26, 2017
 (Best and Easy) Support Vector Machines(SVM) + HOG Tutorial | OpenCV 3.0, 3.1, 3.2, 3.3 |
Windows 10 | Visual Studio 2015 | x64 | Train & TestNovember 24, 2017
 OpenCV 3.3.1 vs 3.3.0 Changes (Release Notes) November 15, 2017
 Turn your Raspberry Pi into old school retro gaming console using RetroPie (Windows &
MAC)November 15, 2017
 OpenCV Real-time Graph Plot using Matplotlib or Python-DrawnowNovember 13, 2017

Search for:
Most Viewed Posts

 (Step by Step) Install OpenCV 3.3 with Visual Studio 2015 on Windows 10 x64 (2017 DIY) (9,602)
 Simple Hand/Finger Tracking & Gesture Recognition (4,342)
 Install OpenCV 3.3 and Python(2.7 & 3.5) bindings on Ubuntu 16.04 (3,727)
 (Easy & Fast) Pre-Compiled OpenCV Libraries and Headers for 3.2 with Visual Studio 2015 x64
Windows 10 Support (3,688)
 (COMPLETE, BEST & EASIEST) ESP8266-01 | ESP8266-12E/F Configuration Guide with Arduino
Nano/Mega/UNO for IoT Projects (Includes all ESP Issues) (3,281)

APRIL 2018

M T W T F S S

« Nov

2 3 4 5 6 7 8

9 10 11 12 13 14 15
APRIL 2018

M T W T F S S

16 17 18 19 20 21 22

23 24 25 26 27 28 29

30

 Home
 Raspberry Pi
 Tutorials Bundle
o (Step by Step)(C++) Install OpenCV 3.3 (Win10) x64 (VS15)
o (Step by Step) (Python 2.7) Install OpenCV 3.3 (Win10) x64
o Simplest Facial Recognition(Ubuntu + Python)
o Simple Vehicle Tracking/Detection System (C++) OpenCV | Windows 10 | x64 | Visual
Studio 2015
o OpenCV : Motion Tracking with Recording using WebCam (Easy Way) aka Motion
Activated Security Camera
o Simple Hand/Finger Tracking & Gesture Recognition
o Fast Object Tracking based on HSV, YUV, RGB & YCrCb Threshold and Contours
Detection with X, Y Coordinates
o Easiest way to install OpenCV on Ubuntu 16.04 (Python + C++ Support)
o Recognizing day to day objects using Object Recognition in OpenCV (C++)
o Simple Digit Recognition aka Optical Character Recognition(OCR) in OpenCV-C++
o Simple Digit Recognition aka Optical Character Recognition(OCR) in OpenCV-Python
o Driver Drowsiness detection using OpenCV and Python
 Guide to ESP Arduino
 OpenCV (c++)
 OpenCV (python)
 SVM + HOG
 DEEP Learning VM
 About Me
 Contact

Copyright © World of OpenCV, AI, Computer Vision and Robotics Examples and Tutorials
2018. All rights reserved.


Sidebar Setup
Please add widgets via the admin area!