Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/dnn/test/npy_blob.cpp
16344 views
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
8
#include "test_precomp.hpp"
9
#include "npy_blob.hpp"
10
11
namespace cv
12
{
13
14
static std::string getType(const std::string& header)
15
{
16
std::string field = "'descr':";
17
int idx = header.find(field);
18
CV_Assert(idx != -1);
19
20
int from = header.find('\'', idx + field.size()) + 1;
21
int to = header.find('\'', from);
22
return header.substr(from, to - from);
23
}
24
25
static std::string getFortranOrder(const std::string& header)
26
{
27
std::string field = "'fortran_order':";
28
int idx = header.find(field);
29
CV_Assert(idx != -1);
30
31
int from = header.find_last_of(' ', idx + field.size()) + 1;
32
int to = header.find(',', from);
33
return header.substr(from, to - from);
34
}
35
36
static std::vector<int> getShape(const std::string& header)
37
{
38
std::string field = "'shape':";
39
int idx = header.find(field);
40
CV_Assert(idx != -1);
41
42
int from = header.find('(', idx + field.size()) + 1;
43
int to = header.find(')', from);
44
45
std::string shapeStr = header.substr(from, to - from);
46
if (shapeStr.empty())
47
return std::vector<int>(1, 1);
48
49
// Remove all commas.
50
shapeStr.erase(std::remove(shapeStr.begin(), shapeStr.end(), ','),
51
shapeStr.end());
52
53
std::istringstream ss(shapeStr);
54
int value;
55
56
std::vector<int> shape;
57
while (ss >> value)
58
{
59
shape.push_back(value);
60
}
61
return shape;
62
}
63
64
Mat blobFromNPY(const std::string& path)
65
{
66
std::ifstream ifs(path.c_str(), std::ios::binary);
67
CV_Assert(ifs.is_open());
68
69
std::string magic(6, '*');
70
ifs.read(&magic[0], magic.size());
71
CV_Assert(magic == "\x93NUMPY");
72
73
ifs.ignore(1); // Skip major version byte.
74
ifs.ignore(1); // Skip minor version byte.
75
76
unsigned short headerSize;
77
ifs.read((char*)&headerSize, sizeof(headerSize));
78
79
std::string header(headerSize, '*');
80
ifs.read(&header[0], header.size());
81
82
// Extract data type.
83
CV_Assert(getType(header) == "<f4");
84
CV_Assert(getFortranOrder(header) == "False");
85
std::vector<int> shape = getShape(header);
86
87
Mat blob(shape, CV_32F);
88
ifs.read((char*)blob.data, blob.total() * blob.elemSize());
89
CV_Assert((size_t)ifs.gcount() == blob.total() * blob.elemSize());
90
91
return blob;
92
}
93
94
} // namespace cv
95
96