OpenCV sub-image from a Mat image

Og Namdik picture Og Namdik · Oct 17, 2012 · Viewed 32.5k times · Source

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

Answer

Quentin Geissmann picture Quentin Geissmann · Oct 17, 2012

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