Is opencv matrix data guaranteed to be continuous?

前端 未结 3 2216
臣服心动
臣服心动 2020-12-02 21:28

I know that, the data contained in an opencv matrix is not guaranteed to be continuous. To make myself clear, here is a paragraph from Opencv documentation:

3条回答
  •  没有蜡笔的小新
    2020-12-02 21:54

    Data stored in OpenCV cv::Mats are not always continuous in memory, which can be verified via API Mat::isContinuous(). Instead, it follows the following rules:

    1. Matrices created by imread(), clone(), or a constructor will always be continuous.
    2. The only time a matrix will not be continuous is when it borrows data from an existing matrix (i.e. created out of an ROI of a big mat), with the exception that the data borrowed is continuous in the big matrix, including
      • borrow a single row;
      • borrow multiple rows but with full original width.

    The following code from my blog demonstrates this in a better way (see the inline comments for further explanation).

    std::vector mats(7);
    
    // continuous as created using constructor
    mats[0] = cv::Mat::ones(1000, 800, CV_32FC3);      
    
    // NOT continuous as borrowed data is not continuous (multiple rows and not full original width)
    mats[1] = mats[0](cv::Rect(100, 100, 300, 200));     
    
    // continuous as created using clone()
    mats[2] = mats[1].clone();               
    
    // continuous for single row always    
    mats[3] = mats[2].row(10);             
    
    // NOT continuous as borrowed data is not continuous (multiple rows and not full original width)         
    mats[4] = mats[2](cv::Rect(5, 5, 100, 2));     
    
    // continuous as borrowed data is continuous (multiple rows with full original width)   
    mats[5] = mats[2](cv::Rect(0, 5, mats[2].cols, 2));
    
    // NOT continuous as borrowed data is not continuous (multiple rows and not full original width) 
    mats[6] = mats[2].col(10);                            
    

提交回复
热议问题