Advertisement
jack06215

[OpenCV] BOW trainer

Mar 3rd, 2020
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <iostream>
  4. #include <fstream>
  5. #include <vector>
  6.  
  7. #include <opencv2/highgui.hpp>
  8. #include <opencv2/xfeatures2d.hpp>
  9. #include <opencv2/core.hpp>
  10. #include <opencv2/features2d.hpp>
  11. #include <opencv2/imgproc.hpp>
  12.  
  13. #include "dlib/image_processing.h"
  14. #include "dlib/string.h"
  15. #include "dlib/opencv.h"
  16.  
  17. std::vector<std::string> labels{ "dolphin", "ibis" };
  18.     std::string filename;
  19.     std::vector<cv::KeyPoint> kpts;
  20.     cv::Mat desc;
  21.     cv::Mat feats_unclustered;
  22.     cv::Ptr<cv::Feature2D> sift_detector = cv::xfeatures2d::SIFT::create();
  23.  
  24.     cv::Mat image;
  25.  
  26.     // Get the keypoints and compute descriptors for all the images in the dataset.
  27.     for (int class_id = 0; class_id < labels.size(); class_id++) {
  28.         for (int image_id = 1; image_id < 51; image_id++) {
  29.             filename = "./data/" + labels[class_id] + "/image_" + dlib::pad_int_with_zeros(image_id, 4) + ".jpg";
  30.             image = cv::imread(filename, cv::IMREAD_GRAYSCALE);
  31.             if (image.empty()) {
  32.                 std::cout << filename << " cannot read\n";
  33.             }
  34.             sift_detector->detectAndCompute(image, cv::Mat(), kpts, desc);
  35.             feats_unclustered.push_back(desc);
  36.         }
  37.     }
  38.  
  39.     // Build the vocabulary by clustering the obtained descriptors and obtain 200 words.
  40.     int dict_size = 200;
  41.     cv::TermCriteria tc(cv::TermCriteria::MAX_ITER, 100, 0.01);
  42.     int retires = 1;
  43.     int flag = cv::KMEANS_PP_CENTERS;
  44.     cv::BOWKMeansTrainer bow_trainer(dict_size, tc, retires, flag);
  45.     cv::Mat dictionary = bow_trainer.cluster(feats_unclustered);
  46.  
  47.     // Save dictionary to YML file
  48.     cv::FileStorage fs("dictionary.yml", cv::FileStorage::WRITE);
  49.     fs << "vocabulary" << dictionary;
  50.     fs.release();
  51.  
  52.     //// write to CSV file
  53.     //std::ofstream ofs;
  54.     //ofs.open("dictionary_trained.csv");
  55.     //ofs << cv::format(dict_trained, cv::Formatter::FMT_CSV) << std::endl;
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement