13

Possible Duplicate:
Understanding region of interest in openCV 2.4

i want to get a sub-image (the one bounded by the red box below) from an image (Mat format). how do i do this?

enter image description here

here's my progress so far:

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);
}
Community
  • 1
  • 1
Og Namdik
  • 823
  • 4
  • 14
  • 22
  • 1
    This question as already been asked and answered, at least [here](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 Oct 17 '12 at 10:01

1 Answers1

29

You can start picking a contour (in your case, the contour corresponding to the hand). Then, you calculate the bounding rectangle for this contour. Finally you make a new matrix header from it.

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);

Warning: In this case, miniMat is a subregion of imgray. This means that if you modify the former, you also modify the latter. Use miniMat.copyTo(anotherMat) to avoid this.

I hope it helped, Good luck

Quentin Geissmann
  • 2,240
  • 1
  • 21
  • 36
  • 1
    thank you! i got an output that has the correct output but also includes other contours. i used RETR_EXTERNAL instead of RETR_TREE so that there will be lesser contours. how do i identify which contour is the correct one? – Og Namdik Oct 17 '12 at 10:51
  • 1
    @OgNamdik You can loop through the contours and calculate area or area of the bounding rectangle (or other parameters) for each. In your case, it seems that you can simply keep the contour that has the biggest area... Also, do not hesitate to accept the answer if you are happy with it. :D – Quentin Geissmann Oct 17 '12 at 11:06