Advertisement
cd62131

CSV with OpenCV cv::Mat

Jun 26th, 2017
1,169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <opencv2/core/core.hpp>
  2. #include <opencv2/core/mat.hpp>
  3. #include <opencv2/core/operations.hpp>
  4. #include <algorithm>
  5. #include <cstdint>
  6. #include <fstream>
  7. #include <iostream>
  8. #include <string>
  9.  
  10. cv::Mat parseCSV(const std::string& path) {
  11.   std::ifstream fin { path };
  12.   std::uint32_t row_size = 0, col_size = 0;
  13.  
  14.   while (!fin.eof()) {
  15.     std::string line;
  16.     std::getline(fin, line);
  17.     if (line.empty())
  18.       break;
  19.     row_size++;
  20.     std::uint32_t col = std::count(line.begin(), line.end(), ',');
  21.     col++;
  22.     col_size = std::max(col, col_size);
  23.   }
  24.   fin.clear();
  25.   fin.seekg(0);
  26.  
  27.   cv::Mat_<int> new_m(row_size, col_size);
  28.   std::uint32_t i = 0, j = 0;
  29.   while (!fin.eof()) {
  30.     std::string line;
  31.     std::getline(fin, line);
  32.     if (line.empty())
  33.       break;
  34.     std::istringstream line_stream { line };
  35.     for (std::string s; std::getline(line_stream, s, ',');) {
  36.       new_m(i, j++) = std::stoi(s);
  37.     }
  38.     ++i;
  39.     j = 0;
  40.   }
  41.   fin.close();
  42.   return new_m;
  43. }
  44.  
  45. void writeCSV(const std::string& path, const cv::Mat& m) {
  46.   std::ofstream fout { path };
  47.   fout << cv::format(m, "csv");
  48.   fout.close();
  49. }
  50.  
  51. int main() {
  52.   std::string path { "data.csv" };
  53.   cv::Mat m = parseCSV(path);
  54.   m.at<int>(0, 0) = 100;
  55. //  std::cout << m << std::endl;
  56.   path = "new_" + path;
  57.   writeCSV(path, m);
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement