双通道 cv::Mat 对象填充 row-col 索引没有 for 循环

Two-channel cv::Mat object filled with row-col indexes without for cycle

我想在OpenCV中创建一个双通道矩阵,其值是对应的行和列索引对。我可以通过以下方式轻松做到这一点:

for (int i = 0 ; i< img_height ; ++ i){
    for (int j = 0 ; j < img_width ; ++ j){
        src.ptr<Point2f>(i)[j] = Point2f(j,i);
    }
}

我想知道 OpenCV 中是否有一种方法可以更快、更紧凑地初始化这样的矩阵,而不必使用这种逐元素的方法。我搜索了文档,但没有找到任何可以帮助我实现此目的的内容。

我这么问是因为我确实需要我的应用程序更快,所以我正在寻找可以应用到我的代码的任何可能的改进。

提前致谢

对此没有内置函数。您最终可以使用 repeat 模拟 Matlab 函数 meshgrid,但在这种情况下会慢得多。

但是您可以改进一些事情:

  • 从内部循环中获取指向行首的指针,因为它对每一行都是相同的。
  • 避免创建临时对象来存储值。
  • 我想你调换了 i 和 j。

看看这段代码:

Mat2f src(img_height, img_width);

for (int i = 0; i < img_height; ++i) {
    Vec2f* ptr = src.ptr<Vec2f>(i);
    for (int j = 0; j < img_width; ++j) {
        ptr[j][0] = i;
        ptr[j][1] = j;
    }
}

此代码段速度稍快(时间以毫秒为单位):

@MarcoFerro:    1.22755
@Miki:          0.818491

测试代码:

#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;

int main()
{
    int img_height = 480;
    int img_width = 640;

    {
        Mat2f src(img_height, img_width);

        double tic = double(getTickCount());
        for (int i = 0; i< img_height; ++i){
            for (int j = 0; j < img_width; ++j){
                src.ptr<Point2f>(i)[j] = Point2f(i, j);
            }
        }

        double toc = (double(getTickCount()) - tic) * 1000.0 / getTickFrequency();
        cout << "@MarcoFerro: \t" << toc << endl;
    }
    {
        Mat2f src(img_height, img_width);

        double tic = double(getTickCount());
        for (int i = 0; i < img_height; ++i) {
            Vec2f* ptr = src.ptr<Vec2f>(i);
            for (int j = 0; j < img_width; ++j) {
                ptr[j][0] = i;
                ptr[j][1] = j;
            }
        }

        double toc = (double(getTickCount()) - tic) * 1000.0 / getTickFrequency();
        cout << "@Miki: \t\t" << toc << endl;
    }

    getchar();
    return 0;
}