Skip to content

Instantly share code, notes, and snippets.

@takiyu
Last active May 13, 2019 14:27
Show Gist options
  • Save takiyu/6532f1325ce492f670f3b99081fc235d to your computer and use it in GitHub Desktop.
Save takiyu/6532f1325ce492f670f3b99081fc235d to your computer and use it in GitHub Desktop.
Eigen<->Numpy Binary Conversion
#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;
}
#!/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
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')
#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