TinyNPY is a tiny, lightweight C++ library for parsing Numpy array files in NPY and NPZ format. No third party dependencies are needed to parse NPY and uncompressed NPZ files, but ZLIB library is needed to parse compressed NPZ files. TinyNPY is easy to use, simply copy the two source files in you project.
#include "TinyNPY.h"
#include <iostream>
int main(int argc, const char** argv)
{
if (argc < 2) {
std::cout << "Usage: demo <file.npy|file.npz>\n";
return -1;
}
// Read a single NPY array file
NpyArray arr;
const LPCSTR ret = arr.LoadNPY(argv[1]);
// NPZ options (uncomment one):
// - Read specific array by name from NPZ
// NpyArray arr; // re-declare if switching examples
// const LPCSTR ret = arr.LoadNPZ(argv[1], "features");
// - Read all arrays from NPZ
// NpyArray::npz_t arrays;
// const LPCSTR ret = NpyArray::LoadNPZ(argv[1], arrays);
// NpyArray& arr = arrays.begin()->second; // use first array (by reference)
if (ret != NULL) {
std::cout << ret << " '" << argv[1] << "'\n";
return -2;
}
// Print array metadata
std::cout << "Number of values: " << arr.NumValue() << "\n";
std::cout << "Size in bytes: " << arr.SizeBytes() << "\n";
std::cout << "Dimensions:";
for (size_t s : arr.Shape()) std::cout << " " << s;
std::cout << "\n";
if (typeid(int) == arr.ValueType())
std::cout << "Value type: int\n";
if (typeid(float) == arr.ValueType())
std::cout << "Value type: float\n";
std::cout << "Order: " << (arr.ColMajor() ? "col-major" : "row-major") << "\n";
return EXIT_SUCCESS;
}
See main.cpp for more details.
TinyNPY is licensed under the MIT License.