2012-10-17 75 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

好的非常感谢你! –