在OpenCV中将某些行从一个矩阵复制到另一矩阵的最快方法 [英] Fastest way to copy some rows from one matrix to another in OpenCV

查看:292
本文介绍了在OpenCV中将某些行从一个矩阵复制到另一矩阵的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个[32678 x 10]矩阵(w2c),我想将其24700行复制到另一个矩阵(out).我有要在vector(index)中复制的行的索引.为此,我这样做:

I have a [32678 x 10] matrix (w2c) and I want to copy 24700 rows of it to another matrix(out). I have the index of the rows to be copied in a vector(index). For doing this in matlab I do:

out = w2c(index_im,:);

大约需要0.002622秒.

It takes approximately 0.002622 seconds.

在OpenCV中:

Mat out(index.cols, w2c.cols, w2c.type());
for (int i = 0; i < index.cols; ++i) {
    w2c.row(index.at<int>(i) - 1).copyTo(out.row(i));
}

大约需要0.015121秒.

It takes approximately 0.015121 seconds.

如您所见,Matlab的速度提高了6倍.如何提高OpenCV代码的效率?

As you can see Matlab is 6 times faster. How can I make the OpenCV code efficient?

我正在使用cmake-2.9,g ++-4.8,opencv-2.4.9,ubuntu 14.04

I am using cmake-2.9, g++-4.8, opencv-2.4.9, ubuntu 14.04

更新:

我在发布模式下运行了代码,结果如下(它仍然比Matlab慢得多)

I ran my code in release mode, here is the result ( It is still significantly slower than Matlab )

RELEASE     DEBUG       MATLAB
0.008183    0.010070    0.001604    
0.009630    0.010050    0.001679
0.009120    0.009890    0.001566
0.007534    0.009567    0.001635
0.007886    0.009886    0.001840

推荐答案

因此,我尝试了不同的方法来解决此问题,并且我能获得比Matlab更好的性能的唯一方法是使用memcpy并直接直接复制数据.

So I tried different methods for this problem and the only way I could achieve a better performance than Matlab was using memcpy and directly copying the data myself.

    Mat out( index.cols, w2c.cols, w2c.type() );
    for ( int i=0;i<index.cols;++i ){
        int ind = index.at<int>(i)-1;
        const float *src = w2c.ptr<float> (ind);
        float *des = out.ptr<float> (i);
        memcpy(des,src,w2c.cols*sizeof(float));
    }

这样,整个过程花费了大约0.001063,这比Matlab快一点.

this way the whole thing took approximately 0.001063 that is a little bit faster than Matlab.

我也发现以这种方式复制数据:

Also I found out that copying data this way:

    Mat out;
    Mat out( index.cols, w2c.cols, w2c.type() );
    for ( int i=0;i<index.cols;++i ){
        int ind = index.at<int>(i)-1;
        out.push_back(w2c.row(ind)); 
    }

比这样复制它快:

    Mat out( index.cols, w2c.cols, w2c.type() );
    for ( int i=0;i<index.cols;++i ){
        int ind = index.at<int>(i)-1;
        w2c.row(ind).copyTo(out.row(i));
    }

但是我不为什么.无论如何,它们都比Matlab慢.

but I don't why. Anyway both of them are slower than Matlab.

这篇关于在OpenCV中将某些行从一个矩阵复制到另一矩阵的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆