How to divide an OpenCV Mat in rectangular sub-reg

2019-03-06 08:30发布

I want to divide a simple Mat (200x200) in different regions (10x10). I make 2 loops, then I create a Rect where I indicate the variables I want in each iteration (x, y, width, height). Finally, I save this region of the image inside a vector of Mats.

But something is wrong with my code:

Mat face = Mat(200, 200, CV_8UC1);
vector<Mat> regions;
Mat region_frame;
int width = face.cols * 0.05;
int heigth = face.rows * 0.05;
for(int y=0; y<=(face.rows - heigth); y+=heigth)
{
    for(int x=0; x<=(face.cols - width); x+=width)
    {
        Rect region = Rect(x, y, x+width, y+heigth);
        region_frame = face(region);
        regions.push_back(region_frame);            
    }
}

The problem is just in the final step, it's not working with size of the new region_frame I try to create. It's increasing with each iteration number of cols.

How can I solve this?

1条回答
倾城 Initia
2楼-- · 2019-03-06 08:51

OpenCV Rect can be constructed as:

Rect(int _x, int _y, int _width, int _height);

So you need to change the line in your code as:

Rect region = Rect(x, y, width, heigth);

It seems that you instead passed the coordinates of the top left and bottom right corners. If you want to do so, use this other constructor:

Rect(const Point& pt1, const Point& pt2);

and you can do like:

Rect region = Rect(Point(x, y), Point(x+width, y+heigth));
查看更多
登录 后发表回答