Matlab到OpenCV的转换-优化

Matlab to OpenCV conversion - optimization?

本文关键字:优化 转换 OpenCV Matlab      更新时间:2023-10-16

我正在将Matlab代码转换为OpenCV"C/cpp"代码。我有一些疑虑如下。

A = [ 2; 10;  7;  1;  3;  6; 10; 10;  2; 10];
ind = [10; 5; 9; 2];

B是a的子矩阵;矩阵B的元素是在ind中指定的位置处的A的元素。

B = [10 3; 2; 10];

在Matlab中,我只使用

B = A(ind);

在C中使用OpenCV、

for ( int i = 0; i < ind.rows; i++) {
    B.at<int>(i,0) = A.at<int>(ind.at<int>(i,0), 0);
}

有没有一种不使用for循环的方法?

如果您正在寻找一种整洁的复制方式。我建议你定义一个函数以下是在给定位置复制的类似STL的实现

#include<vector>
#include<cstdio>
using namespace std;
/**
 * Copies the elements all elements of B to A at given positions.
 * indexing array ranges [ind_first, ind_lat)
 * e.g 
 *   int A[]= {0, 2, 10,  7,  1,  3,  6, 10, 10,  2, 10};
 *   int B[] = {-1, -1, -1, -1};
 *   int ind[] = {10, 5, 9, 2};
 *   copyat(B, A, &ind[0], &ind[3]);
 *   // results: A:[0,2,10,7,1,-1,6,10,10,-1,-1]
 */
template<class InputIterator, class OutputIterator, class IndexIterator>
OutputIterator copyat (InputIterator src_first, 
               OutputIterator dest_first, 
               IndexIterator ind_first, 
               IndexIterator ind_last)
{
    while(ind_first!=ind_last) {
    *(dest_first + *ind_first) = *(src_first);
    ++ind_first;
    }
    return (dest_first+*ind_first);
}

int main()
{
    int A[]= {0, 2, 10,  7,  1,  3,  6, 10, 10,  2, 10};
    int B[] = {-1, -1, -1, -1};
    int ind[] = {10, 5, 9, 2};
    copyat(B, A, &ind[0], &ind[3]);
    printf("A:[");
    for(int i=0; i<10; i++)  
    printf("%d,", A[i]);
    printf("%d]n",A[10]);
}