npy_blob.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // This file is part of OpenCV project.
  2. // It is subject to the license terms in the LICENSE file found in the top-level directory
  3. // of this distribution and at http://opencv.org/license.html.
  4. //
  5. // Copyright (C) 2017, Intel Corporation, all rights reserved.
  6. // Third party copyrights are property of their respective owners.
  7. #include "test_precomp.hpp"
  8. #include "npy_blob.hpp"
  9. namespace cv
  10. {
  11. static std::string getType(const std::string& header)
  12. {
  13. std::string field = "'descr':";
  14. int idx = header.find(field);
  15. CV_Assert(idx != -1);
  16. int from = header.find('\'', idx + field.size()) + 1;
  17. int to = header.find('\'', from);
  18. return header.substr(from, to - from);
  19. }
  20. static std::string getFortranOrder(const std::string& header)
  21. {
  22. std::string field = "'fortran_order':";
  23. int idx = header.find(field);
  24. CV_Assert(idx != -1);
  25. int from = header.find_last_of(' ', idx + field.size()) + 1;
  26. int to = header.find(',', from);
  27. return header.substr(from, to - from);
  28. }
  29. static std::vector<int> getShape(const std::string& header)
  30. {
  31. std::string field = "'shape':";
  32. int idx = header.find(field);
  33. CV_Assert(idx != -1);
  34. int from = header.find('(', idx + field.size()) + 1;
  35. int to = header.find(')', from);
  36. std::string shapeStr = header.substr(from, to - from);
  37. if (shapeStr.empty())
  38. return std::vector<int>(1, 1);
  39. // Remove all commas.
  40. shapeStr.erase(std::remove(shapeStr.begin(), shapeStr.end(), ','),
  41. shapeStr.end());
  42. std::istringstream ss(shapeStr);
  43. int value;
  44. std::vector<int> shape;
  45. while (ss >> value)
  46. {
  47. shape.push_back(value);
  48. }
  49. return shape;
  50. }
  51. Mat blobFromNPY(const std::string& path)
  52. {
  53. std::ifstream ifs(path.c_str(), std::ios::binary);
  54. CV_Assert(ifs.is_open());
  55. std::string magic(6, '*');
  56. ifs.read(&magic[0], magic.size());
  57. CV_Assert(magic == "\x93NUMPY");
  58. ifs.ignore(1); // Skip major version byte.
  59. ifs.ignore(1); // Skip minor version byte.
  60. unsigned short headerSize;
  61. ifs.read((char*)&headerSize, sizeof(headerSize));
  62. std::string header(headerSize, '*');
  63. ifs.read(&header[0], header.size());
  64. // Extract data type.
  65. CV_Assert(getType(header) == "<f4");
  66. CV_Assert(getFortranOrder(header) == "False");
  67. std::vector<int> shape = getShape(header);
  68. Mat blob(shape, CV_32F);
  69. ifs.read((char*)blob.data, blob.total() * blob.elemSize());
  70. CV_Assert((size_t)ifs.gcount() == blob.total() * blob.elemSize());
  71. return blob;
  72. }
  73. } // namespace cv