sub2Ind matlab to c++/opencv conversion

sub2Ind matlab to c++/opencv conversion

本文关键字:opencv conversion c++ matlab to sub2Ind      更新时间:2023-10-16

我正在尝试用c ++创建此代码/我正在使用openCV,但不必这样做。

 wi = size(Gr, 2);
 he = size(Gr, 1);
 cropFactor = 0.10;
 [x, y] = meshgrid( round(cropFactor * wi):round( (1-cropFactor)*wi ), round(cropFactor * he):round((1-cropFactor)*he) );
 xy = sub2ind(size(Gr), y(:), x(:));

这是我到目前为止所拥有的

    int width = dst.cols;
    int height = dst.rows;
    double cropFactor = 0.10;

    cv::Mat1i X,Y;
    Utilities::Meshgrid(Utilities::MatlabRound(cropFactor * width), Utilities::MatlabRound((1 - cropFactor) * width), Utilities::MatlabRound(cropFactor * height), Utilities::MatlabRound((1-cropFactor) * height),X, Y);       
    Utilities::Sub2Ind(width, height, X, Y);

round() 函数

int Utilities::MatlabRound(double numberToRound)
{
    return floor( numberToRound + 0.5);
}

这是我的网格网格()函数,它按预期工作

void Utilities::Meshgrid(int startX, int endX, int startY, int endY, cv::Mat1i &X, cv::Mat1i & Y)
{
    std::vector<int> vec_x, vec_y;
    for (int i = startX; i <= endX; i++)
    {
        vec_x.push_back(i);
    }
    for (int i = startY; i <= endY; i++)
    {
        vec_y.push_back(i);
    }
    cv::Mat x = cv::Mat(vec_x);
    cv::Mat y = cv::Mat(vec_y);
    cv::repeat(x.reshape(1,1), y.total(), 1, X);
    cv::repeat(y.reshape(1,1).t(), 1, x.total(), Y);
}

但是我无法理解什么是下标以及如何实现 Sub2Ind 函数

你能解释一下吗?

更新我已经实现了sub2ind,请参阅我的答案

我已经为 2D 矩阵实现了 sub2Ind它经过测试并工作正常

cv::Mat Utilities::Sub2Ind(int width, int height, cv::Mat X, cv::Mat Y)
{
    /*sub2ind(size(a), rowsub, colsub)
    sub2ind(size(a), 2     , 3 ) = 6
    a = 1 2 3 ;
    4 5 6
    rowsub + colsub-1 * numberof rows in matrix*/
    std::vector<int> index;
    cv::transpose(Y,Y);
    cv::MatConstIterator_<int> iterX = X.begin<int>(), it_endX = X.end<int>();
    cv::MatConstIterator_<int> iterY = Y.begin<int>(), it_endY = Y.end<int>();
    for (int j = 0; j < X.cols; ++j,++iterX)    
    {
        //running on each col of y matrix
        for (int i =0 ;i < Y.cols; ++i,++iterY )
        {   
            int rowsub = *iterY;
            int colsub = *iterX;
            int res = rowsub + ((colsub-1)*height);
            index.push_back(res);
        }
        int x = 5;
    }   
    cv::Mat M(index) ;
    return M;   
}