c++ - OpenCV:无法将数据正确传递给函数

标签 c++ opencv

使用 MSVS2010 在 Windows 上编译

在下面的代码中,我尝试使用线迭代器,然后在沿线提取像素值后,我试图将提取的数据传递给函数 foo():

图像是单 channel 16 位 png。

int foo(unsigned short int *values,  unsigned int nSamples)
{
    cout<<"address in PlotMeNow"<<endl;
    cout<<&values[0]<<endl; 
    cout<<"values in PlotMeNow"<<endl;

    for(int i=0;i<5;i++){
        cout<<values[i]<<endl;
    }
    return 0;  
}

unsigned short int * IterateLine(Mat image)
{
    LineIterator it(image, Point(1,1), Point(5,5), 8);
    vector<ushort> buf;

    for(int i = 0; i < it.count; i++, it++){
        buf.push_back(image.at<ushort>(it.pos()));
    }

    std::vector<ushort> data(5);
    data=buf; 

    cout<<"the  address in the iterateLine() is"<<endl; 
    cout<<&data[0]<<endl; 

    cout<<"values in IterateLine"<<endl;
    for(int i=0;i<5;i++){
        cout<<data[i]<<endl;
    }
     return &data[0]; 
}

int main()
{

    Mat img = imread("sir.png", CV_LOAD_IMAGE_ANYCOLOR | CV_LOAD_IMAGE_ANYDEPTH);
    unsigned short int * x ; 
    //Iterate through the line  
    x =  IterateLine(img); 

    int n=5; 
    foo(&x[0], n);

    cout<<"The address in main() is"<<endl; 
    cout<<x<<endl; 
    cout<<"values in main are"<<endl;

    for(int i=0;i<5;i++){  
        cout<<x[i]<<endl;
    }     
    getch();
    return 0 ; 
}

程序的输出是:

the address in the iterateLine() is
001195D8
values in IterateLine
40092
39321
39578
46003
46774
address in foo()
001195D8
values in foo()
56797
56797
56797
56797
56797
The address in main() is
001195D8
values in main() are
56797
56797
56797
56797
56797

可以看出 foo()main() 的值是错误的。它应该与 IterateLine() 报告的相同。由于地址已正确传递(请参阅输出),因此使用指针我应该从任何函数获取相同的数据。但它没有发生。

为什么会发生这种情况以及如何将数据正确传递给 foo()

最佳答案

void IterateLine( const Mat& image, vector<ushort>& linePixels, Point p1, Point p2 )
{
    LineIterator it(image, p1,p2, 8);

    for(int i = 0; i < it.count; i++, it++){
        linePixels.push_back(image.at<ushort>(it.pos()));
    }
}

int main()
{

    Mat img = imread("sir.png", CV_LOAD_IMAGE_ANYCOLOR | CV_LOAD_IMAGE_ANYDEPTH);

    vector<ushort> linePixels;        // initially empty
    IterateLine( img, linePixels, Point(1,1), Point(5,5) );  

    foo( &linePixels[0], linePixels.size() );

    return 0 ; 
}

关于c++ - OpenCV:无法将数据正确传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24608386/

相关文章:

c++ - 我似乎无法修复的意外错误

c++ - 内存转储分析(应用挂起)

python - 如何使用 OpenCV 的重映射功能?

c++ - OpenGL - 在 3D 场景之上错误地绘制 2D 叠加层

c++ - 从模板类继承

c++ - 围绕 avcodec_open/close 的线程锁定

c++ - 3 channel 图像上的OpenCV CUDA拉普拉斯滤波器

android - 是否可以使用 OpenCV android 端口销售商业 android 应用程序?

c++ - 桌面应用程序中的 WinRT GUI

OpenCV GetCapture属性 : Identifier Not Found?