OpenCV从正方形向量中提取图像的面积
OpenCV extract area of an image from a vector of squares
我有一张包含一个正方形的图像,我需要提取该正方形中包含的面积。在应用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;
}
相关文章:
- 在RAW图像中提取RGB通道值的库或方法
- 使用ffmpeg时如何提高图像导出/提取速度?
- 如何在使用OpenCV C++应用K均值后提取分割图像
- 提取带有边框环绕的图像中的子图像
- 从Dlib CNN中提取图像
- 如何从C 中的CV :: MAT图像中有效提取某些像素
- 如何从我自己的图像中提取PCD文件
- 使用OpenCV从图像中提取不同尺寸的矩形
- 图像和图像处理中的特征提取
- 如何在 OpenCv 中使用 HSV 阈值和轮廓从图像中提取皮肤
- 如何从彩色图像中提取和计算相似颜色点的数量
- C++使用逐位操作从图像中提取字符
- 如何从图像中提取ROI区域并将其显示在窗口中
- 如何从Opencv中的图像矩阵中提取数值梯度矩阵
- 如何从图像中提取FAST功能
- 提取一组样本图像的描述符,并在OpenCV中训练SVM
- 使用 GrabCut 提取背景图像
- 如何从图像中提取人脸
- 从JPEG图像中提取RGB,使用libjpeg c++库
- OpenCV从正方形向量中提取图像的面积