我正在尝试在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,请参见我的回答

最佳答案

我已经为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;
}

关于c++ - 将sub2Ind Matlab转换为C++/OpenCV,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27881713/

10-11 14:50