OpenCV indexing through Mat of unknown type

后端 未结 2 577
失恋的感觉
失恋的感觉 2021-01-03 00:34

I would like to access the elements of a matrix of unknown type:

for(int ii = 0; ii < origCols; ii++)
{
  colIdx.at(0,ii) = ii+1; // mak         


        
2条回答
  •  一生所求
    2021-01-03 01:17

    After looking through some of the docs, I don't think there is a native OpenCV way to do it without avoiding branching.

    If you are just concerned about cleaner code, you could try a template approach so long as you don't mind templates:

    template  void dostuff(cv::Mat& colIdx, int origCols)
    {
       for(int ii = 0; ii < origCols; ii++)
       {
           colIdx.at(0,ii) = (T)(ii+1); // make one based index
       }
    }
    
    void dostuff_poly(cv::Mat& colIdx, int origCols)
    {
        switch(colIdx.type())
        {
            case CV_8UC1: dostuff(colIdx, origCols); break;
            case CV_32FC1: dostuff(colIdx, origCols); break;
            case CV_64FC1: dostuff(colIdx, origCols); break;
            // and so on
            default:
        }
    }
    

    In this example, the code is rather small, so templates seems like it wouldn't be a bad choice and would give you the polymorphism you want without writing a bunch of redundant code.

    Maybe some of these tutorials would give you a better idea:

    OpenCV docs: core module tutorials

    OpenCV docs: How to scan images

提交回复
热议问题