bosslegend33
bosslegend33

Reputation: 21

How to?: defining cv::Mat as class member and then modify it in source code file

I defined a class which has a cv::Mat data member. Then in a class method I wish to modify this matrix somehow (change values, adding rows/cols, etc).

However, I keep getting a Segmentation Fault error (I'll put the errors at the bottom).

I thought about using cv::Mat& reference instead of cv::Mat as data member of the class, but then it becomes 'messy' because they have to be initialized.

I suspect I have to use smart pointers somehow but my background is more in C rather than C++.

If someone can give a step by step explanation I would very much appreciate it. Thanks.

//Header file
class A
{
     public:
         A();
         void do_something();

     private:
         cv::Mat data;
}

//Source code file
#include "A.h"

A::A():data(cv::Mat()){}

void A::do_something()
{
   cv::Mat tmp(2,2,CV_32FC1, cv::Scalar(6));
   data = tmp;
   //also other mehtods fail like
   //data = tmp.clone();
   //data.push_back(2);
}

Segmentation fault errors I get:

Upvotes: 1

Views: 2571

Answers (1)

bosslegend33
bosslegend33

Reputation: 21

First of all, thanks for the help of everybody who replied; they made me somehow notice my mistake. And an apology because it was very dumb.

The problem was that in my main function in test.cpp, I declared a pointer to class A, but I was not initializing it with the 'new' command. So I guess data cv::Mat was not initialized properly causing the Segmentation Fault.

//test.cpp
#include "A.h" 

int main()
{
    A* a;
    //a = new A(); //this line was missing in my program
    a->do_something();

    return 0;
}

Upvotes: 1

Related Questions