返回cv:Mat指向main函数的指针

时间:2018-04-09 21:58:17

标签: c++ opencv c++11 image-processing

我编写了一个属于类panoramic_distance的函数。此函数将images/cv:Mat的数组返回到main函数。但我有点困惑如何从main函数访问图像数组的内容,因为当我调用cv::imshow时附加代码给我分段错误。

class panoramic_distance 
{  
    cv::Mat* breakimageinstrips(cv::Mat image, bool vertical, int no_strips)
    {      
        cv:Mat split_image[6];
        int d_factor;

        d_factor=image.cols/3;
        split_image[0] = image(Rect(0,0,d_factor,image.rows));
        split_image[1] = image(Rect(d_factor,0,d_factor,image.rows));
        split_image[2] = image(Rect((2*d_factor),0,d_factor,image.rows));
        std::cout<<"\n Image slip in 3";
        std::cout<<" address = "<<split_image;
        split_images1=split_image;
        std::cout<<" addressss = "<<split_images1;
        return split_images1;


        return split_image;
    }     

};

int main( int argc, char** argv )
{
    panoramic_distance p1;
    cv::Mat *images;
    images=p1.breakimageinstrips(t1,1,3);
    std::cout<<" \n"<<images<<std::endl;  
    cv::imshow("This image",*(image));
    return 0;
}

如果我提交cv::imshow那么它不会给出分段错误并且有后续输出。这意味着cv:Mat数组的地址被转移到main但我不知道如何访问数组的内容。代码没有错,但问题是如何访问main函数中的cv:Mat数组内容。

输出:

0x47d6ecfa0

Image slip in 3 address = 0x7ffe7d6ecbd0 addressss = 0x7ffe7d6ecbd0
0x7ffe7d6ecbd0

RUN FINISHED; exit value 0; real time: 10ms; user: 0ms; system: 0ms

2 个答案:

答案 0 :(得分:4)

您将返回指向本地数组(第一项)的指针。函数返回后,该数组不再存在。它被称为悬空指针,它为您提供正式的未定义行为,最好避免使用。

自从我涉足OpenCV以来已经很久了,但是我记得cv::Mat本身就像一个智能指针,你可以直接按价值返回。

答案 1 :(得分:1)

非常抱歉提前发布。我有解决方案。

     class panoramic_distance
{  
void breakimageinstrips(cv::Mat image, bool vertical, int no_strips, cv::Mat split_image[])

           //cv:Mat split_image[6];
           int d_factor;

                   d_factor=image.cols/3;
                   split_image[0] = image(Rect(0,0,d_factor,image.rows));
                   split_image[1] = image(Rect(d_factor,0,d_factor,image.rows));
                   split_image[2] = image(Rect((2*d_factor),0,d_factor,image.rows));
                   std::cout<<"\n Image slip in 3";
                   std::cout<<" address = "<<split_image;





         }     

};
int main( int argc, char** argv )
{
 panoramic_distance p1;
 cv::Mat images[6]

 p1.breakimageinstrips(t1,1,3, images);
 cv::imshow("This image",images[0]);
 cv::imshow("This image",images[1]);
 cv::imshow("This image",images[2]);
 return 0;
}