我有一个包含一个正方形的图像,我需要提取那个正方形中包含的区域。在应用了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);
}为了为原始图像中检测到的所有方格生成一个名为子图像的新Mat
卡尔记得我,在图像中检测到的点可能不是一个完美的正方形(正如你在上面的图像中所看到的),但是我刚才向您建议的代码假设它们代表了。
实际上,我得到了这个错误:
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让剧本也接受非完美方块的建议?
发布于 2011-10-13 14:49:14
我觉得我需要澄清一些关于该代码的内容。
First,它假设检测到的区域是一个完美的平方,因为它忽略了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);编辑
在阅读2.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;
}https://stackoverflow.com/questions/7755647
复制相似问题