Alperen AYDIN Alperen AYDIN - 2 years ago 98
C++ Question

Why do I get a seg fault when I try input a value in OpenCV?

So I have this piece of code:

if(channels == 3)
type = CV_32FC3;
type = CV_32FC1;
cv::Mat M(rows,cols,type);
std::cout<<"Cols:"<<cols<<" ColsMat:"<<M.cols<<std::endl;
float * source_data = (float*);
// copying the data into the corresponding pixel
for (int r = 0; r < rows; r++)
float* source_row = source_data + (r * rows * channels);
for (int c = 0; c < cols ; c++)
float* source_pixel = source_row + (c * channels);
for (int ch = 0; ch < channels; ch++)
std::cout<<"Row:"<<r<<" Col:"<<c<<" Channel:"<<ch<<std::endl;
std::cout<<"Type check: "<<typeid(T_M(0,r,c,ch)).name()<<std::endl;
float* source_value = source_pixel + ch;
*source_value = T_M(0, r, c, ch);

T_M is an Eigen::Tensor

I first thought that I got the error from T_M but it isn't the case.

I tried accessing *source_value and I am mostly sure that is the source of the error.

Funny thing is that I don't get the error in the end or the beginning. I get the seg fault around the middle.
For example, with rows: 915, cols: 793, and channels:1

I get the error at Row:829 Col:729 Channel:0.

I can't figure out the source of this error.

Answer Source

you compute your row pointer wrong, should be cols instead of rows:

float* source_row = source_data + (r * cols   * channels);

In general, you must be very careful when you use a flat representation of a matrix, it's really error-prone.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download