wildcat
wildcat

Reputation: 285

MATLAB sub2ind / ind2sub in OpenCV /C++

Are there any functions in OpenCV which are equal to MATLAB's sub2ind and ind2sub functions? I need both functions for my C++ app. If OpenCV lacks of these functions, are there any C++ libs which provide equivalent functionality?

Upvotes: 6

Views: 4337

Answers (2)

Gilad
Gilad

Reputation: 6595

Here is my code for 2D matrix. I have tested it.

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

Upvotes: 0

paghdv
paghdv

Reputation: 564

You can write them yourself:

int sub2ind(const int row,const int col,const int cols,const int rows)
{
   return row*cols+col;
}

void ind2sub(const int sub,const int cols,const int rows,int &row,int &col)
{
   row=sub/cols;
   col=sub%cols;
}

Upvotes: 8

Related Questions