【问题标题】:OpenCV cv::Mat to short* (avoiding memcpy)OpenCV cv::Mat to short*(避免 memcpy)
【发布时间】:2013-04-26 14:43:02
【问题描述】:

我有一个要从其他人的 C# 应用程序调用的 C++ 函数。作为输入,我的函数得到一个有符号短整数数组、它所代表的图像的尺寸以及为返回数据分配的内存,即另一个有符号短整数数组。这将代表我的函数的标题:

my_function (short* input, int height, int width, short* output)

在我的函数中,我从 input 创建了一个 cv::Mat,如下所示:

cv::Mat mat_in = cv::Mat (height, width, CV_16S, input);

这个mat_in 然后被转换为CV_32F 并由OpenCV 的cv::bilateralFilter 处理。在它返回 cv::Mat mat_out 后,我​​将数据转换回CV_16SbilateralFilter 只接受CV_8UCV_32F)。现在我需要将这个cv::Mat mat_out 转换回一个短整数数组,以便它可以返回给调用函数。这是我的代码:

my_function (short* input, int height, int width, short* output)
{
    Mat mat_in_16S = Mat (height, width, CV_16S, input);

    Mat mat_in_32F = Mat (height, width, CV_32F);
    Mat mat_out_CV_32F = Mat (height, width, CV_32F);

    mat_in_16S.convertTo (mat_in_32F, CV_32F);

    bilateralFilter (mat_in_32F, mat_out_32F, 5, 160, 2);
    Mat mat_out_16S = Mat (mat_in_16S.size(), mat_in_16S.type());
    mat_out_32F.convertTo (mat_out_16S, CV_16S);

    return 0;
}

显然,在最后的某个地方,我需要将mat_out_16S 中的数据放入output。我的第一次尝试是返回参考:

output = &mat_out_16S.at<short>(0,0);

但我当然意识到这是一个愚蠢的想法,因为mat_out_16S 在函数返回后立即超出范围,留下output 指向空虚。目前我最好的尝试如下(来自this question):

memcpy ((short*)output, (short*)mat_out_16S.data, height*width*sizeof(short));

现在我想知道,有没有更好的方法?复制所有这些数据感觉有点低效,但我看不出我还能做什么。不幸的是,我无法返回 cv::Mat。如果没有更好的方法,我目前的memcpy 方法至少安全吗?我的数据都是 2 字节有符号短整数,所以我认为填充不应该有问题,但我不想遇到任何不愉快的意外。

【问题讨论】:

    标签: c++ pointers opencv return memcpy


    【解决方案1】:

    您可以将此constructor 用于您的mat_out_16S

    Mat::Mat(Size size, int type, void* data, size_t step=AUTO_STEP)
    

    所以你的功能是:

    my_function (short* input, int height, int width, short* output)
    {
        Mat mat_in_16S = Mat (height, width, CV_16S, input);
    
        Mat mat_in_32F = Mat (height, width, CV_32F);
        Mat mat_out_CV_32F = Mat (height, width, CV_32F);
    
        mat_in_16S.convertTo (mat_in_32F, CV_32F);
    
        bilateralFilter (mat_in_32F, mat_out_32F, 5, 160, 2);
        Mat mat_out_16S = Mat (mat_in_16S.size(), mat_in_16S.type(), output);
        mat_out_32F.convertTo (mat_out_16S, CV_16S);
    
        return 0;
    }
    

    【讨论】:

    • 我运行了代码,一切都很好,如果我遇到任何问题,我会在这里留下更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 2012-12-04
    相关资源
    最近更新 更多