Last active
May 13, 2019 14:27
-
-
Save takiyu/6532f1325ce492f670f3b99081fc235d to your computer and use it in GitHub Desktop.
Eigen<->Numpy Binary Conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <eigen3/Eigen/Core> | |
#include <cstdlib> | |
int main(int argc, char const* argv[]) { | |
// Create matrix | |
Eigen::MatrixXf mat(10, 20); | |
for (size_t y = 0; y < 10; y++) { | |
for (size_t x = 0; x < 20; x++) { | |
mat(y, x) = static_cast<float>(20 * y + x) / 10.f; | |
} | |
} | |
std::cout << "1: Eigen:" << mat << std::endl; | |
// Save to file | |
FILE *fp; | |
if ((fp = fopen("eigen_out.dat", "wb")) == NULL) { | |
fprintf(stderr, "Error: cannot open file %s\n", fp); | |
exit(1); | |
} | |
fwrite(mat.data(), sizeof(float), mat.size(), fp); | |
fclose(fp); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
g++ first.cpp -o first.out | |
./first.out | |
python3 second.py | |
g++ third.cpp -o third.out | |
./third.out | |
diff numpy_out.dat eigen_out.dat |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
mat = np.fromfile('eigen_out.dat', dtype='<f') | |
mat = mat.reshape(20, 10) | |
mat = np.transpose(mat) # Because eigen is column major by default | |
print(f'2: numpy: {str(mat)}') | |
mat = np.transpose(mat) | |
mat.tofile('numpy_out.dat') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <eigen3/Eigen/Core> | |
#include <cstdlib> | |
int main(int argc, char const* argv[]) { | |
Eigen::MatrixXf mat(10, 20); | |
FILE *fp; | |
if ((fp = fopen("eigen_out.dat", "rb")) == NULL) { | |
fprintf(stderr, "Error: cannot open file %s\n", fp); | |
exit(1); | |
} | |
fread(mat.data(), sizeof(float), mat.size(), fp); | |
fclose(fp); | |
std::cout << "3: Eigen:" << mat << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment