-1

I don't know why c++'s rule says that I can't return local variable?

this simple "max" function totally has no problem;

int max(int a,int b)
{
    int maxnum;
    if(a>b)maxnum= a;
    else maxnum= b;
    return maxnum;
}
int main( int argc, char** argv )
{
    cout<<max(10,30);
    system("PAUSE");
    return 0;
}

but, when I want to return local variable as before in opencv,it turns out wrong data

why can't I return local variable here?

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <sstream>
using namespace cv;
using namespace std;

Mat GetIntensity(Mat *pic,int y,int x)
{
    float Array[6];
    for(int i=0;i<6;i++)
    {
        Array[i]=pic[i].at<uchar>(y,x);
    }
    Mat Intensity(6,1,CV_32FC1,&Array);
    cout<<Intensity;
    return Intensity;
}

int main( int argc, char** argv )
{
    stringstream ss;
    string pic_name;
    Mat pic[6];
    for(int i=0;i<6;i++)
    {
        ss.clear();
        ss.str(std::string());
        ss<<"pic"<<i<<".bmp"<<endl;
        ss>>pic_name;
        pic[i] = imread(pic_name, CV_LOAD_IMAGE_GRAYSCALE);
        if(! pic[i].data )
        {// Check for invalid input
            cout <<  "Could not open or find the image" << endl ;
            system("pause");
            return -1;
        }
        //namedWindow( pic_name, CV_WINDOW_AUTOSIZE );
        // Create a window for display.
        //imshow(pic_name, pic[i] );
    }
    cout<<=GetIntensity(pic,60,60);

    system("PAUSE");
    //waitKey(0);
    return 0;
}
user3094631
  • 425
  • 3
  • 13

1 Answers1

1

your construct here uses a local array to hold the values. this will get invalid, once your Mat leaves the scope:

Mat GetIntensity(Mat *pic,int y,int x)
{
    float Array[6]; //problem
    for(int i=0;i<6;i++)
    {
        Array[i]=pic[i].at<uchar>(y,x);
    }
    Mat Intensity(6,1,CV_32FC1,&Array); // problem
    cout<<Intensity;
    return Intensity;
}

better create a Mat with it's own data:

Mat GetIntensity(Mat *pic,int y,int x)
{
    Mat Intensity(6,1,CV_32FC1); // no problem
    for(int i=0;i<6;i++)
    {
        Intensity.at<float>(i) = pic[i].at<uchar>(y,x);
    }
    cout<<Intensity;
    return Intensity;
}
berak
  • 39,159
  • 9
  • 91
  • 89