Hello guys I am doing a program that calculates the eigenvalues and the eigenvectors of an image. For this I am using the OpenCV and Armadillo libraries, with OpenCV I upload the image to my program and with Armadillo I calculate the eigenvalues and the eigenvectors.
I need to convert from cv::Mat to arma::mat to be able to calculate the eigenvalues and eigenvectors, for this I do the following based on a previous answer:
arma::mat arma_mat(reinterpret_cast<double*>(image.data), image.rows, image.cols);
The full code is here:
#include<armadillo>
#include<opencv2/opencv.hpp>
#include<iostream>
int main()
{
cv::Mat image = cv::imread("Imgs/face.jpg", CV_LOAD_IMAGE_GRAYSCALE);
if(!image.data){
std::cout << "No se pudo cargar la imágen\n";
return -1;
}
arma::mat arma_mat(reinterpret_cast<double*>(image.data), image.rows, image.cols);
return 0;
}
The code has no problem compiling, but when it is executed, when it reaches the line where it converts from cv::Mat to arma::mat the execution stops and the console appears (exit value: -1) Does anyone know why this is happening?
Don't use reinterpret cast unless you really know what you are doing. See the accepted answer of this question for a good explanation of what it does.
I have no experience with opencv, only with armadillo. Looking at opencv documentation I can see that image.data
is an uchar
. You can't just reinterpret_cast the values to double. It is undefined behavior and definitely wrong in this case.
The armadillo matrix class (arma::Mat
) is a template. You can create a Mat<uchar>
and use the Mat<uchar>(ptr_aux_mem, n_rows, n_cols, copy_aux_mem = true, strict = false)
constructor to avoid the copy of the elements. Of course you can also use other armadillo types, but in that case you would need to copy the elements in order to convert to the other type (such as to arma::mat
, which is just an alias to arma::Mat<double>
). In that case you would use a different constructor.