I'm trying to use Eigen to interface with unsigned char * types. I can convert to Eigen and then to float, but when I convert back to unsigned char , the result is wrong. I need the Eigen matrix to be in float type so I can perform arithmetic operations on it. Then I need to bring it back to unsigned char so I can save it.
#include <Eigen/Dense>
#include <iostream>
int main(){
unsigned char* data;
for (int i=0;i<9;++i){
data[i]= i;
}
//Map data to Eigen
Map<Matrix<unsigned char,3,3> ,RowMajor> img(data,3,3);
//Convert to float
MatrixXf gray = img.cast<float>();
//Convert back to unsigned char*
float *gray_array = gray.data();
unsigned char *gray_UC = (unsigned char*)gray_array;
std::cout<<"Eigen matrix converted to unsigned char:"<<(float)*(gray_UC+1)<<std::endl;
std::cout<<"Eigen matrix as float: "<<*(gray_array+i)<<std::endl;
std::cout<<"Original data converted to float: "<<(float)*(data+1)<<std::endl;
}
Data being an unsigned char* type.
I expect gray_UC and data to be the same, but it is not the case. Even more, gray_array prints the right float value, so it might be the conversion to unsigned char that is wrong.