OpenCV从正方形向量中提取图像的面积

OpenCV extract area of an image from a vector of squares

本文关键字:图像 提取 正方形 向量 OpenCV      更新时间:2023-10-16

我有一张包含一个正方形的图像,我需要提取该正方形中包含的面积。在应用squares.c脚本(在每个OpenCV发行版的示例中可用)之后,我获得了一个正方形向量,然后我需要为每个正方形保存一个图像。

用户karlphillip建议:

for (size_t x = 0; x < squares.size(); x++) 
{
    Rect roi(squares[x][0].x, squares[x][0].y, 
             squares[x][1].x - squares[x][0].x, 
             squares[x][3].y - squares[x][0].y);
    Mat subimage(image, roi);
}
为原始图像 中检测到的所有正方形生成一个名为subimage的新Mat

正如karl记得我的,图像中检测到的点可能不代表一个完全平方(正如你在上面的图像中看到的),但我刚才给你建议的代码假设它们是完全平方的。

实际上我得到了这个错误:

OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width &&
      roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height &&
      roi.y + roi.height <= m.rows) in Mat, file /usr/include/opencv/cxmat.hpp, 
      line 187
terminate called after throwing an instance of 'cv::Exception'
what():  /usr/include/opencv/cxmat.hpp:187: error: (-215) 0 <= roi.x && 
       0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y &&
       0 <= roi.height && roi.y + roi.height <= m.rows in function Mat
Aborted

让脚本也接受非完全平方的建议?

我觉得我需要澄清一些关于这段代码的事情。

首先,它假设检测到的区域是一个完全平方,因为它忽略了squares[x]内部的一些点来创建一个新的Mat

第二个,它也假设构成区域的点是顺时针方向检测的,从图像左上角的p0开始:

(p0)  1st----2nd  (p1)
       |      |
       |      |
(p3)  4th----3rd  (p2)

,这可能并不适用于所有检测到的区域。这意味着这段代码:

Rect roi(squares[x][0].x, squares[x][0].y, 
         squares[x][1].x - squares[x][0].x, 
         squares[x][3].y - squares[x][0].y);

可能会产生无效尺寸的ROI,例如负宽度和高度值,这就是为什么OpenCV在Mat subimage(image, roi);上向您抛出cv::Exception

你应该做的是写一段代码,将区域的左上角点命名为p0,然后是它在右侧最近的邻居p1,然后找到该区域的右下角点并命名为p2,然后左边是p3。在此之后,组装ROI就很容易了:

Rect roi(p0.x, p0.y, 
         p1.x - p0.x, 
         p3.y - p0.y);

编辑:

我在阅读OpenCV v2.3的文档时发现了一个优秀的解决方案。它自动化了我之前描述的过程,它使事情变得如此简单和干净。您可以使用此技巧将向量中的4个点排序为有意义的Rect结构:

// Data returned and filled by findSquares(). Check the example squares.cpp for more info on this function.
vector<vector<Point> > squares;
for (size_t i = 0; i < squares.size(); i++)
{
    Rect rectangle = boundingRect(Mat(squares[i]));
    cout << "#" << i << " rectangle x:" << rectangle.x << " y:" << rectangle.y << " " << rectangle.width << "x" << rectangle.height << endl;
}