簡體   English   中英

OpenCV從正方形矢量中提取圖像的區域

[英]OpenCV extract area of an image from a vector of squares

我有一個包含正方形的圖像,我需要提取該正方形中包含的區域。 在應用了square.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

建議使腳本也接受非完美的方塊?

我覺得我需要澄清一些有關該代碼的內容。

首先 ,它假設檢測到的區域是一個完美的正方形,因為它忽略了square 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 Mat subimage(image, roi);

您應該做的是編寫一個代碼,該代碼將識別該區域的左上角並將其稱為p0 ,然后它在右側最近的neightbor, 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM