c++ - Matlab 到 OpenCV 的转换 - 优化?

标签 c++ c matlab opencv code-conversion

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

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

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

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]);
}

关于c++ - Matlab 到 OpenCV 的转换 - 优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14873874/

相关文章:

c++ - g++/gcc 中 char 的符号及其历史

c++ - 通过 map.equal_range 问题 interator

matlab - 更改 8 位整数的最后一位

matlab - 如何在Matlab中使用系统矩阵获得多输入多输出系统的传递函数

c++ - getaddrinfo() 函数抛出错误 n 11003

c++ - 在eclipse中构建cpp项目的问题

c - 为什么这个程序的输出是 312213444 而不是 3122134?

c - 将结构定义放在函数原型(prototype)之前,但结构需要来自 argv 的信息

mysql - mysql 中的并行查询执行

matlab - 在 MEX 文件中检索 C 中的错误消息字符串