Mint.K
Mint.K

Reputation: 899

c++ OpenCV Rect size increasing

I am trying to learn how cv::Rect() works. I have a 200x200 image and I'd like break this image into 3x3 rectangles. Here's my code:

for(int y = 0; y < img.rows; y+=3;) // img.rows = 200
{
    for(int x =0; x < img.cols; x+=3){ // img.cols = 200
        cv:: Rect my_region = cv::Rect(x, y, x + 3, y + 3);
        Mat my_mat = img(my_region).clone();
        int mat_Size = mymat.total(); 
        cout << "region size: " << mat_Size << endl;
        if(x==6){  // test up to 6
           return - 1;
        }
    }
}

mat_size should be consistently 9 because I am generating 3x3 rectangles. However, it's actually increasing by 9 every time: 9 -> 18 -> 27. Which is not what I intended to do. How do I fix it? Please help.

Upvotes: 1

Views: 585

Answers (1)

Daniel R.
Daniel R.

Reputation: 784

The use of cv::Rect(x, y, x + 3, y + 3); is not in your sense because the last parameters does not mean the coordinates of lower right corner of the Rectangle as you are thinking. Having a look at the OpenCV doc or into types.hpp, you will have

template<typename _Tp> inline
Rect_<_Tp>::Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height)
: x(_x), y(_y), width(_width), height(_height) {}

The last 2 parameters stands for width and height of the Rectangle, so to fix your code, you will need cv::Rect my_region = cv::Rect(x, y, 3, 3);

Upvotes: 4

Related Questions