2012-10-17 140 views
10

可能重複:
Understanding region of interest in openCV 2.4OpenCV的子圖像

我想從圖像獲取子圖像(一個由下面的紅色框爲界) (墊格式)。我該怎麼做呢?

enter image description here

這是我迄今取得的進展:

include <opencv2/core/core.hpp> 
#include <opencv2/highgui/highgui.hpp> 
#include <opencv2/imgproc/imgproc.hpp> 

using namespace std; 
using namespace cv; 
int main() 
{ 
    Mat imgray, thresh; 
    vector<vector<Point> >contours; 
    vector<Point> cnt; 
    vector<Vec4i> hierarchy; 
    Point leftmost; 

    Mat im = imread("igoy1.jpg"); 
    cvtColor(im, imgray, COLOR_BGR2GRAY); 
    threshold(imgray, thresh, 127, 255, 0); 
    findContours(thresh, contours, hierarchy, RETR_TREE,CHAIN_APPROX_SIMPLE); 
} 
+1

這個問題如已被提問和回答,至少[這裏](http://stackoverflow.com/questions/12705817/understanding-region-of-interest- in-opencv-2-4/12706208#12706208)and [there](http://stackoverflow.com/questions/12369697/access-sub-matrix-of-a-multidimensional-mat-in-opencv/12370641#12370641 ) – remi

回答

24

你可以開始採摘的輪廓(在你的情況下,對應於手的輪廓)。 然後,您計算該輪廓的邊界矩形。 最後,你從它製作一個新的矩陣標題。

int n=0;// Here you will need to define n differently (for instance pick the largest contour instead of the first one) 
cv::Rect rect(contours[n]); 
cv::Mat miniMat; 
miniMat = imgray(rect); 

警告:在這種情況下,是MINIMAT的imgray的子​​區域。這意味着如果你修改前者,你也修改後者。使用miniMat.copyTo(anotherMat)來避免這種情況。

我希望它的幫助下, 好運

+1

謝謝!我得到了一個具有正確輸出但還包含其他輪廓的輸出。我使用了RETR_EXTERNAL而不是RETR_TREE,因此會有較小的輪廓。我如何識別哪個輪廓是正確的? –

+1

@OgNamdik您可以遍歷輪廓並計算每個邊界矩形(或其他參數)的面積或面積。就你而言,看起來你可以簡單地保持最大面積的輪廓...此外,如果你對此感到滿意,請不要猶豫,接受答案。 :D –

+0

好的非常感謝你! –