#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/ml/ml.hpp>
#include <opencv2/gpu/gpu.hpp>
#include <fstream>
#include <iomanip>
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#define Feature_dim 3780
using namespace Std;
using namespace CV;
Class Mysvm:public CVSVM
{
Public
Obtaining an Alpha array in the decision function of the SVM
Double * Get_alpha_vector ()
{
Return this->decision_func->alpha;
}
The rho parameter in the decision function that obtains the SVM, that is, the offset
Float Get_rho ()
{
Return this->decision_func->rho;
}
};
int main ()
{
#if 0
Mat image;
Image = Imread ("D:\\dataset\\temp\\6.png");
Hogdescriptor Hog;
Vector<float> v_feature;
Hog.compute (image, V_feature, Cv::size (8, 8));
Hog.compute (image, V_feature, Cv::size (16, 16));
int featurevecsize = V_feature.size ();
cout << "****************************************haha****************" << Endl;
cout << featurevecsize << Endl;
#else
//***************************************************************************************************
Initialization
//***************************************************************************************************
Char positivepath[256] = "d:\\dataset\\inriaperson\\train\\pos\\"; Change path
Char negativepath[256] = "d:\\dataset\\inriaperson\\train\\neg\\";
Char testpath[256] = "d:\\dataset\\inriaperson\\test\\pos\\";
Char positivepath[256] = "d:\\dataset\\inriaperson\\train_64x128_h96\\pos\\";
Char negativepath[256] = "d:\\dataset\\inriaperson\\train_64x128_h96\\neg\\";
Char testpath[256] = "d:\\dataset\\inriaperson\\70x134h96\\test\\pos\\";
Char testpath[256] = "d:\\dataset\\inriaperson\\test_64x128_h96\\pos\\";
Char testpath[256] = "d:\\dataset\\inriaperson\\test_64x128_h96\\neg\\";
Char classifiersavepath[256] = "D:\\dataset\\inriaperson\\myresult";
int positivesamplecount = 614; Change data
int negativesamplecount = 1218;
int positivesamplecount = 100;
int negativesamplecount = 100;
int totalsamplecount = Positivesamplecount + negativesamplecount;
int testsamplecount = 1126;
int testsamplecount = 100;
Cvmat *samplefeaturesmat = Cvcreatemat (Totalsamplecount, Feature_dim, CV_32FC1); Dimension of redirect Quantity
Cvsetzero (Samplefeaturesmat);
Cvmat *samplelabelmat = Cvcreatemat (Totalsamplecount, 1, CV_32FC1);
Cvsetzero (Samplelabelmat);
Cvmat *testfeaturesmat = Cvcreatemat (Testsamplecount, Feature_dim, CV_32FC1); Parameter 1764? Positive 288, minus 453
Cvmat *testfeaturesmat = Cvcreatemat (1, Feature_dim, CV_32FC1); Parameter 1764? Positive 288, minus 453
Cvsetzero (Testfeaturesmat);
Cvmat *testlabelmat = Cvcreatemat (Testsamplecount, 1, CV_32FC1);//Sample identification
Cvsetzero (Testlabelmat);
Float testlabelmat[288] = {0.0};
Mat Samplefeaturesmat ();
Hogdescriptor Hog (Size (+), size (8, 8), size (8, 8), 9),//hog detector, used to calculate the hog descriptor
Vector<float> v_feature;
//***************************************************************************************************
Characteristics of a positive case
//***************************************************************************************************
Positive file read-in
Ifstream fin (Positivepath, ios::in);
if (!fin)
//{
cout << "Positivepath can not open the file!" << Endl;
return-1;
//}
Char positiveimage[256];
string path;
String S_positiveimage;
for (int i = 0; i < Positivesamplecount; i++)
{
Picture Name Modification
memset (Positiveimage, ' n ', sizeof (positiveimage));
sprintf (Positiveimage, "%d.png", i + 1); Do you want to change to. jpg?
S_positiveimage = Positiveimage;
Path = Positivepath + s_positiveimage;
Mat image = Imread (path);
if (Image.data = = NULL)
{
cout << "Positive image sample Load Error:" << i << "<< path << Endl;
System ("pause");
Continue
}
Hog Feature Extraction
Gpu::hogdescriptor Hog (Size (+), size (8, 8), size (8, 8), 9); Seems to have some parameters, overloaded?
Hogdescriptor Hog (Size (+), size (8, 8), size (8, 8), 9);
Hogdescriptor Hog;
Vector<float> v_feature;
Image = Image (Rect (16, 16, 64, 128));
Hog.compute (image, V_feature, Cv::size (8, 8));
Hog.compute (image, V_feature, Cv::size (16, 16));
int featurevecsize = V_feature.size ();
cout << "****************************************haha****************" << Endl;
cout << featurevecsize<<endl;
return 0;
for (int j = 0; j<featurevecsize; j + +)
{
SAMPLEFEATURESMAT[I][J] = V_feature[j];
Cv_mat_elem (*samplefeaturesmat, float, I, j) = V_feature[j]; Cv_mat_elem What do you mean?
}
Samplelabelmat->data.fl[i] = 1; What is the. fl[]?
cout << "Positive" << i + 1 << "is running ..." << Endl;
}
Fclose (Fin);
//***************************************************************************************************
Characteristics of negative cases
//***************************************************************************************************
Negative file read-in
Ifstream fin (Negativepath, ios::in);
if (!fin)
//{
cout << "Can not open the file!" << Endl;
return-1;
//}
Char negativeimage[256] = ""; Initialize it?
String S_negativeimage;
for (int i = 0; i < Negativesamplecount; i++)
{
Picture Name Modification
Hog Feature Extraction
memset (NegativeImage, ' n ', sizeof (negativeimage));
sprintf (NegativeImage, "%d.png", i + 1); Do you want to change to. jpg?
S_negativeimage = NegativeImage;
Path = Negativepath + s_negativeimage;
cout << "********************************************************" <<endl;
cout << path<<endl;
Mat image = Imread (path);
if (Image.data = = NULL)
{
cout << "Positive image sample Load Error:" << i << "<< path << Endl;
System ("pause");
Continue
}
Hog Feature Extraction
Gpu::hogdescriptor Hog (Size (+), size (8, 8), size (8, 8), 9); Seems to have some parameters, overloaded?
Hogdescriptor Hog (Size (+), size (8, 8), size (8, 8), 9);
Hogdescriptor Hog;
Vector<float> v_feature;
Image = Image (Rect (16, 16, 64, 128));
Hog.compute (image, V_feature, Cv::size (8, 8));
int featurevecsize = V_feature.size ();
cout << "***************************lalala*****************************" << Endl;
cout << featurevecsize;
for (int j = 0; j<featurevecsize; j + +)
{
Cv_mat_elem (*samplefeaturesmat, float, Positivesamplecount + i, j) = V_feature[j]; Cv_mat_elem What do you mean?
}
Samplelabelmat->data.fl[positivesamplecount + i] = 0; What is the. fl[]?
cout << "negative" << i + 1 << "is running ..." << Endl;
}
//**********************************************************************************************
//Linear SVM Training
//**********************************************************************************************
// Set the parameter
Cvsvmparams params;
Params.svm_type = svm::c_svc;
Params. C = 0.01;
Params.kernel_type = svm::linear;
//params.term_crit = Termcriteria (cv_termcrit_iter, (int) 1e7, 1e-6);
Params.term_crit = Cvtermcriteria (Cv_termcrit_iter, Flt_epsilon);
//Training
cout << starting training process << Endl;
CVSVM SVM;
MYSVM SVM;
Svm.train (Samplefeaturesmat, Samplelabelmat, Mat (), Mat (), params);
cout << "finished training process" << Endl;
//**********************************************************************************************
//Result Save
//classifiersavepath Read into
//ifstream fin (Classifiersavepath, ios::in);
if (!fin)
//{
//cout << "Positivepath can not open the file!" << Endl;
return-1;
//}
//svm.save (Classifiersavepath);
//cvreleasemat (&samplefeaturesmat);
//cvreleasemat (&samplelabelmat);
//cout << "has saved succeeded!" << Endl;
//**********************************************************************************************
//test
//test file read-in
Ifstream fin (Testpath, ios::in);
//if (!fin)
//{
//cout << "can not open the file!" << Endl;
return-1;
//}
Char testimage[256] = ""; Initialize
string s_testimage;
for (int i = 0; i < Testsamplecount; i++)
{
//Picture name Modify
//hog feature Extraction
memset (testimage, ' + ', sizeof (testimage));
sprintf (testimage, "%d.png", i + 1);//Do you want to change to. jpg
S_testimage = testimage;
Path = Testpath + s_testimage;
Mat image = Imread (path);
if (image.data = = NULL)
{
cout << "positive image sample Load Error:" << i << "" << PA th << Endl;
System ("pause");
Continue;
}
//hog feature extraction
//gpu::hogdescriptor hog (Size (+), size (8, 8), size (8, 8), 9);//seems to have some parameters, overloaded?
//hogdescriptor Hog (Size (+), size (8, 8), size (8, 8), 9);
//hogdescriptor Hog;
//vector<float> v_feature;
Image = Image (Rect (16, 16, 64, 128));
Hog.compute (image, V_feature, Cv::size (8, 8));
Int featurevecsize = V_feature.size ();
//cout << "***************************lalala*****************************" << Endl;
//cout << featurevecsize << Endl;
for (int j = 0; j<featurevecsize; j + +)
{
//cv_mat_elem (*testfeaturesmat, float, I, j) = V_feature[j];//cv_ma T_elem What do you mean
Cv_mat_elem (*testfeaturesmat, float, 0, j) = V_feature[j];
}
Float response = svm.predict (Testfeaturesmat);
//testlabelmat->data.fl[i] = response;//.fl[]
Testlabelmat[i] = response;
}
Float right = 0;
for (int i = 0; i < Testsamplecount; i++)
{
//if (testlabelmat->data.fl[i] = = 1)
if (testlabelmat[i] = = 1)
{
right++;
}
}
Float radio = right/testsamplecount;
cout << "The radio of the train is:" << radio << Endl;
/*************************************************************************************************
After the linear SVM training is completed, there is an array, called the support vector, and an array called alpha, with a floating-point number called Rho;
Multiply the alpha matrix with the support vector, and note that Alpha*supportvector will get a column vector. After that, the column is then added to the last element of the vector rho.
In this way, it becomes a classifier that uses the classifier to directly replace the default classifier (Cv::hogdescriptor::setsvmdetector ()) for pedestrian detection in OpenCV,
You can use the classifier trained by your training samples for pedestrian detection.
***************************************************************************************************/
int descriptordim = Svm.get_var_count ();//The dimension of the eigenvector, that is, the dimension of the Hog descriptor
int supportvectornum = Svm.get_support_vector_count ();//number of support vectors
cout << "Number of support vectors:" << supportvectornum << Endl;
Mat Alphamat = Mat::zeros (1, Supportvectornum, cv_32fc1),//alpha vector, length equals number of support vectors
Mat Supportvectormat = Mat::zeros (Supportvectornum, Descriptordim, CV_32FC1);//Support Vector matrix
Mat Resultmat = Mat::zeros (1, Descriptordim, cv_32fc1),//alpha vector multiplied by the support vector matrix result
Copy support vector data into the Supportvectormat matrix
for (int i = 0; i<supportvectornum; i++)
{
Const FLOAT * Psvdata = svm.get_support_vector (i);//Returns a data pointer to the support vector
for (int j = 0; j<descriptordim; j + +)
{
cout<<pdata[j]<< "";
Supportvectormat.at<float> (i, j) = Psvdata[j];
}
}
Copy the alpha vector data into the Alphamat
Double * Palphadata = Svm.get_alpha_vector ();//the Alpha vector in the decision function that returns the SVM
for (int i = 0; i<supportvectornum; i++)
{
Alphamat.at<float> (0, i) = Palphadata[i];
}
Calculation-(Alphamat * supportvectormat), results are put into Resultmat
Gemm (Alphamat, Supportvectormat,-1, 0, 1, resultmat);//Don't know why add the minus sign?
Resultmat =-1 * alphamat * SUPPORTVECTORMAT;
Get the detector available in the final setsvmdetector (const vector<float>& Detector) parameter
Vector<float> Mydetector;
Copy data from Resultmat to array mydetector
for (int i = 0; i<descriptordim; i++)
{
Mydetector.push_back (resultmat.at<float> (0, i));
}
Finally add the offset rho to get the detector
Mydetector.push_back (Svm.get_rho ());
cout << "feature vector dimension:" << svm.get_var_count () << Endl;
cout << "Detection of sub-dimensions:" << mydetector.size () << Endl;
Set the hogdescriptor of the test
cout << "Default detection sub-dimensions" << hog.getdefaultpeopledetector (). Size () <<endl;
Hog.setsvmdetector (Hogdescriptor::getdefaultpeopledetector ());
cout<< "Feature description sub:" <cout << "description of sub-dimensions:" << v_feature.size () << Endl;
Hog.setsvmdetector (Mydetector); //#############################
cout << "debug:" << Endl;
Saving the detection sub-parameters to a file
Ofstream fout ("HOGDetectorForOpenCV.txt");
for (int i = 0; I<mydetector.size (); i++)
{
Fout << Mydetector[i] << Endl;
}
/************** read into the picture for hog pedestrian detection ******************/
Mat src = imread ("00000.jpg");
Mat src = imread ("2007_000423.jpg");
Mat src = imread ("d:\\dataset\\temp\\1.jpg");
Vector<rect> found, found_filtered;//rectangular box array
cout << "Multi-scale hog human detection" << Endl;
Hog.detectmultiscale (SRC, found, 0, size (8, 8), size (32, 32), 1.05, 2);//multi-scale pedestrian detection of images
cout << "Number of rectangles found:" << found.size () << Endl;
Find all the rectangles without nested R, and put in found_filtered, if there is nesting, then take the largest outside rectangle box into the found_filtered
for (int i = 0; i < found.size (); i++)
{
Rect r = found[i];
int j = 0;
for (; J < Found.size (); j + +)
if (j! = I && (R & found[j]) = = R)
Break
if (j = = Found.size ())
Found_filtered.push_back (R);
}
Draw a rectangle because the hog detects a rectangle that is slightly larger than the actual body frame, so there are some adjustments that need to be made here.
for (int i = 0; I<found_filtered.size (); i++)
{
Rect r = found_filtered[i];
R.x + = Cvround (r.width*0.1);
R.width = Cvround (r.width*0.8);
R.y + = Cvround (r.height*0.07);
R.height = Cvround (r.height*0.8);
Rectangle (src, r.tl (), R.Br (), Scalar (0, 255, 0), 3);
}
Imwrite ("imgprocessed.jpg", SRC);
Namedwindow ("src", 0);
Imshow ("src", SRC);
Waitkey ();//NOTE: Imshow must be added after Waitkey, otherwise the image cannot be displayed
#endif
return 0;
}
hog+svm+ detection person (instead of default parameters)