如何在矩形子区域中划分OpenCV Mat

How to divide an OpenCV Mat in rectangular sub-regions?

本文关键字:划分 OpenCV Mat 区域      更新时间:2023-10-16

我想将一个简单的Mat (200x200)划分为不同的区域(10x10)。我做了两个循环,然后我创建了一个Rect,在这里我指出了我想要的变量在每次迭代中(x, y, width, height)。最后,我将图像的这个区域保存在Mat s的vector中。

但是我的代码有问题:

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);            
    }
}

问题只是在最后一步,它不与我尝试创建的新region_frame的大小一起工作。它随着cols的迭代次数而增加。

我该如何解决这个问题?

OpenCV Rect可以构造为:

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

所以你需要改变你的代码行:

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

看起来你传递的是左上角和右下角的坐标。如果您想这样做,请使用另一个构造函数:

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

,你可以这样做:

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