sub2Ind matlab 到 c++/opencv 的转换

sub2Ind matlab to c++/opencv conversion

我正在尝试用 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);
}

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

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 请看我的回答

我已经为二维矩阵实现了 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;   
}