JNIEXPORT void JNICALL Java_org_opencv_objdetect_HOGDescriptor_save_11 (JNIEnv* env, jclass , jlong self, jstring filename) { static const char method_name[] = "objdetect::save_11()"; try { LOGD("%s", method_name); HOGDescriptor* me = (HOGDescriptor*) self; //TODO: check for NULL const char* utf_filename = env->GetStringUTFChars(filename, 0); String n_filename( utf_filename ? utf_filename : "" ); env->ReleaseStringUTFChars(filename, utf_filename); me->save( n_filename ); return; } catch(const std::exception &e) { throwJavaException(env, &e, method_name); } catch (...) { throwJavaException(env, 0, method_name); } return; }
/** * Main program entry point * @param argc unused * @param argv unused * @return EXIT_SUCCESS (0) or EXIT_FAILURE (1) */ int main(int argc, char** argv) { // <editor-fold defaultstate="collapsed" desc="Init"> HOGDescriptor hog; // Use standard parameters here hog.winSize = Size(64, 128); // Default training images size as used in paper // Get the files to train from somewhere static vector<string> positiveTrainingImages; static vector<string> negativeTrainingImages; static vector<string> validExtensions; validExtensions.push_back("jpg"); validExtensions.push_back("png"); validExtensions.push_back("ppm"); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Read image files"> getFilesInDirectory(posSamplesDir, positiveTrainingImages, validExtensions); getFilesInDirectory(negSamplesDir, negativeTrainingImages, validExtensions); /// Retrieve the descriptor vectors from the samples unsigned long overallSamples = positiveTrainingImages.size() + negativeTrainingImages.size(); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Calculate HOG features and save to file"> // Make sure there are actually samples to train if (overallSamples == 0) { printf("No training sample files found, nothing to do!\n"); return EXIT_SUCCESS; } /// @WARNING: This is really important, some libraries (e.g. ROS) seems to set the system locale which takes decimal commata instead of points which causes the file input parsing to fail setlocale(LC_ALL, "C"); // Do not use the system locale setlocale(LC_NUMERIC,"C"); setlocale(LC_ALL, "POSIX"); printf("Reading files, generating HOG features and save them to file '%s':\n", featuresFile.c_str()); float percent; /** * Save the calculated descriptor vectors to a file in a format that can be used by SVMlight for training * @NOTE: If you split these steps into separate steps: * 1. calculating features into memory (e.g. into a cv::Mat or vector< vector<float> >), * 2. saving features to file / directly inject from memory to machine learning algorithm, * the program may consume a considerable amount of main memory */ fstream File; File.open(featuresFile.c_str(), ios::out); if (File.good() && File.is_open()) { #if TRAINHOG_USEDSVM == SVMLIGHT // Remove following line for libsvm which does not support comments File << "# Use this file to train, e.g. SVMlight by issuing $ svm_learn -i 1 -a weights.txt " << featuresFile.c_str() << endl; #endif // Iterate over sample images for (unsigned long currentFile = 0; currentFile < overallSamples; ++currentFile) { storeCursor(); vector<float> featureVector; // Get positive or negative sample image file path const string currentImageFile = (currentFile < positiveTrainingImages.size() ? positiveTrainingImages.at(currentFile) : negativeTrainingImages.at(currentFile - positiveTrainingImages.size())); // Output progress if ( (currentFile+1) % 10 == 0 || (currentFile+1) == overallSamples ) { percent = ((currentFile+1) * 100 / overallSamples); printf("%5lu (%3.0f%%):\tFile '%s'", (currentFile+1), percent, currentImageFile.c_str()); fflush(stdout); resetCursor(); } // Calculate feature vector from current image file calculateFeaturesFromInput(currentImageFile, featureVector, hog); if (!featureVector.empty()) { /* Put positive or negative sample class to file, * true=positive, false=negative, * and convert positive class to +1 and negative class to -1 for SVMlight */ File << ((currentFile < positiveTrainingImages.size()) ? "+1" : "-1"); // Save feature vector components for (unsigned int feature = 0; feature < featureVector.size(); ++feature) { File << " " << (feature + 1) << ":" << featureVector.at(feature); } File << endl; } } printf("\n"); File.flush(); File.close(); } else { printf("Error opening file '%s'!\n", featuresFile.c_str()); return EXIT_FAILURE; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Pass features to machine learning algorithm"> /// Read in and train the calculated feature vectors printf("Calling %s\n", TRAINHOG_SVM_TO_TRAIN::getInstance()->getSVMName()); TRAINHOG_SVM_TO_TRAIN::getInstance()->read_problem(const_cast<char*> (featuresFile.c_str())); TRAINHOG_SVM_TO_TRAIN::getInstance()->train(); // Call the core libsvm training procedure printf("Training done, saving model file!\n"); TRAINHOG_SVM_TO_TRAIN::getInstance()->saveModelToFile(svmModelFile); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Generate single detecting feature vector from calculated SVM support vectors and SVM model"> printf("Generating representative single HOG feature vector using svmlight!\n"); vector<float> descriptorVector; vector<unsigned int> descriptorVectorIndices; // Generate a single detecting feature vector (v1 | b) from the trained support vectors, for use e.g. with the HOG algorithm TRAINHOG_SVM_TO_TRAIN::getInstance()->getSingleDetectingVector(descriptorVector, descriptorVectorIndices); // And save the precious to file system saveDescriptorVectorToFile(descriptorVector, descriptorVectorIndices, descriptorVectorFile); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Test detecting vector"> // Detector detection tolerance threshold const double hitThreshold = TRAINHOG_SVM_TO_TRAIN::getInstance()->getThreshold(); // Set our custom detecting vector hog.setSVMDetector(descriptorVector); hog.save(cvHOGFile); printf("Testing training phase using training set as test set (just to check if training is ok - no detection quality conclusion with this!)\n"); detectTrainingSetTest(hog, hitThreshold, positiveTrainingImages, negativeTrainingImages); printf("Testing custom detection using camera\n"); VideoCapture cap(-1); // open the default camera if(!cap.isOpened()) { // check if we succeeded printf("Error opening camera!\n"); return EXIT_FAILURE; } Mat testImage; while ((cvWaitKey(10) & 255) != 27) { cap >> testImage; // get a new frame from camera cvtColor(testImage, testImage, CV_BGR2GRAY); // Work on grayscale images as trained detectTest(hog, hitThreshold, testImage); imshow("HOG custom detection", testImage); } // </editor-fold> return EXIT_SUCCESS; }