1

I am using OpenCV for image manipulation in C. Please forgive me if this question is answered in the documentation, but I have found the OpenCV docs to be pretty badly formed and difficult to read.

I have an CvMat* that i have extracted from an image file as below:

CvMat* mat = cvLoadImageM((char*) filename, CV_LOAD_IMAGE_COLOR);

What I need to do is get a subimage of that by cropping out a certain bounded region. A logical command for this might be:

CvMat* subMat = cvGetSubImage(mat, minx, maxx, miny, maxy);

where minx, maxx, miny, and maxy define the boundaries of the cropped region. Is there a built in way to do this easily?

ewok
  • 20,148
  • 51
  • 149
  • 254

3 Answers3

8

Take a look at http://nashruddin.com/OpenCV_Region_of_Interest_(ROI)/

In which the tutorial does the following on a Region of Interest:

cvSetImageROI(img1, cvRect(10, 15, 150, 250));
IplImage *img2 = cvCreateImage(cvGetSize(img1),
                           img1->depth,
                           img1->nChannels);
cvCopy(img1, img2, NULL);
cvResetImageROI(img1);

OpenCV has built in capabilities for setting the region which you care about and copying that region out of an image, just as you want to achieve.

Pyrce
  • 8,296
  • 3
  • 31
  • 46
4

If you want a sub-pixel accurate rectangular section of a src image use cvGetRectSubPix or cv::getRectSubPix (this creates an individual copy of all the data, this is not a ROI!)

Example:

cv::Size size(dst_width,dst_height);
cv::Point2f center(src_centerx,src_center_y);
cv::Mat dst;
cv::getRectSubPix(src,size, center,dst,CV_8U);
Oliver Zendel
  • 2,695
  • 34
  • 29
2

Generally this is done by cropping an ROI (region of interest). This blog post goes into some detail on cropping:

/* load image */
IplImage *img1 = cvLoadImage("elvita.jpg", 1);

/* sets the Region of Interest
   Note that the rectangle area has to be __INSIDE__ the image */
cvSetImageROI(img1, cvRect(10, 15, 150, 250));

/* create destination image
   Note that cvGetSize will return the width and the height of ROI */
IplImage *img2 = cvCreateImage(cvGetSize(img1),
                               img1->depth,
                               img1->nChannels);

/* copy subimage */
cvCopy(img1, img2, NULL);

/* always reset the Region of Interest */
cvResetImageROI(img1);

To convert between IplImage (legacy OpenCV) and cvMat (OpenCV 2.x), simply use the cvMat constructor or look at this question for more methods.

Community
  • 1
  • 1
David Titarenco
  • 32,662
  • 13
  • 66
  • 111
  • http://stackoverflow.com/questions/14756505/croping-an-image-in-ios-uisng-opencv-face-detect I facing cropping problem in iphone with opencv. Can please have a look.. My ROI are getting wrong I gues.. – 2vision2 Feb 07 '13 at 19:02