Search code examples
pythonc++opencvmatrix-indexing

Fast indexing in C++ OpenCV


I am quite comfortable with OpenCV in Python. I recently switched to the C++ version, and I keep having problems with the cv::Mat indexing, since I'm too used to numpy's arrays. In particular, I am trying to find if there is a better way of acting on a restricted area of an array without iterating through it. For example, let's say I have a 10x15 unitary matrix and I would like to put everything but the last row to zero (or to another random number); in Python, I would do something like this:

import numpy as np

a = np.ones([10,15])
a[:-1,:-1] = 0

How can I achieve that in C++, having defined cv::Mat a = cv::Mat::ones(10, 15, CV_32FC1);?


Solution

  • The best way is probably to use regions of interest. A cv mat can easily be partitioned by using a rect in the following way:

    using namespace cv;
    
    Mat a = Mat::ones(10, 15, CV_32FC1);
    Rect rect(2, 2, 4, 4);
    Mat roi = a(rect);
    

    you can hereafter modify the roi in whatever fashion you like, put back in a by:

     roi.copyTo(a(rect));
    

    You can elegantly use a new Rect in the previous line, as long as its width and height are the same as the original Rect. To solve your specific question, the easiest way is to make a new matrix with all zeros, and then use copyTo with that one.